Filed Under (Python) by Marcin Kuźmiński on February-8-2010

I’d created another simple application in pylons, final step was to translate it from English to Polish.

I used the babel extractor recommended by pylons and that went really smooth.

My application have a language selector available anytime from menu.
I saw that even this switch worked very well for mako templates and string inside controllers,
it did not work when displaying my custom messages that i over rid in validators
and also did not work in my own custom validators that inherit from FancyValidator.
So i started to investigate this.

The first problem of not translating custom error messages in the regular formencode validators was easily being fixed by using lazy_ugettex method.

def _(s):
    #fix for translation error messages
    return lazy_ugettext(s)

This method allowed me to use lazy_ugettext to translate.
So now when in the validators your translating a string using _(‘this string is for translate’) method it’s actually wrapper for lazy_ugettext function.
Lazy translation is when you translate a string when it is accessed, not when the _() or other functions are called.

The second problem of translating custom error messages in your own validator was a bigger problem

I was looking for a solution for some time, and found a nice trick. You have to use your own
state_obj with static _() function. As example below for custom validation function.

class ValidLoginNames(formencode.validators.FancyValidator):

    messages = {'invalid_name':_('you cannot use %(username)s as login')}

    def validate_python(self, value, state):
        banned_names = ['admin', 'administrator', 'root']
        if value in banned_names:
            raise formencode.Invalid(self.message('invalid_name', state = State_obj, username = value), value, state)

#this is needed to translate the messages using _()
class State_obj(object):
    _ = staticmethod(_)

Those two trick now let’s you translate custom validators without a problem.



Filed Under (Editors, Python) by Marcin Kuźmiński on November-15-2009

I installed new eclipse on ubuntu 9.10, and noticed that manu of FINISH,
NEXT buttons are not working correctly ( you can’t click them).

So it found out it’s eclipse bug, but fortunately there is a simple
solution to this problem.

Write a startup script:

#!/bin/sh
export GDK_NATIVE_WINDOWS=1
/path_to_eclipse/eclipse

Save it as eclipse-run.sh make it +x, and the buttons will work now if you
run your eclipse via the run script.



Filed Under (Mercurial, Nginx) by Marcin Kuźmiński on November-15-2009

Today is a great day ;) i switched my repos from svn to mercurial.
I was still thinking about GIT but there where three key points that made me choose mercurial

Cons: it’s slower than GIT ( but who cares :D )

So after installing mercurial and moving my svn repos with history with hgsvn ( which can also do push to svn )
I started to setup easy access to the repository using nginx. I’ll show you how to setup an SSL http based repository to do PUSH/PULL/CLONE what ever.

Firstly we have to make self signed ssl certificates.
I found on of the easiest tutorials available you can find it here: http://www.akadia.com/services/ssh_test_certificate.html

OK when we have the ssl certificates for our server. Put it somewhere on the server so nginx can access it.
We have to setup a new virtual host for nginx that will only do ssl connections
and have basic auth additionally.

Here’s the example config:

server {
    listen          443;
    server_name     hg.yourserver.com;
    ssl    on;
    ssl_certificate    /home/ssl_certs/hg_cert.crt;
    ssl_certificate_key     /home/ssl_certs/hg_cert.key;
    access_log      /var/log/nginx/hg.log;
    auth_basic      "mercurial server";
    auth_basic_user_file    /etc/nginx/.htpasswd;

    location / {
        proxy_pass      http://127.0.0.1:8001;
        #here's where the hg server runs
        include         /etc/nginx/proxy.conf;
    }
}

Few thing to notice.
.htpasswd file has to be in a format <username>:<cryptPassword> if you don’t have apache
installed you can use my password generator for generating crypt password. This username
and password will be used to do pull/push from console and eclipse.
Another important thing is that when you run hg serve you must specify the -a 127.0.0.1 option which is
for the address the mercurial server runs. Hg serve default is to start at all interfaces
so you have this port open outside and your ssl/passwd protection is for nothing…

I run my using hg serve –webdir-conf=/etc/hg/hgweb.conf -d -p 8001 -a 127.0.0.1

The hgweb.conf should be with

push_ssl = false
#since nginx is doing the SSL
allow_push = * #NGINX  is doing the auth
style = gitweb

O and one more thing remember that your repo should be accessible to hg serv.
I made a mistake and run hg serve as www-data and my repo was to my home user,
and i had internal server error when trying to do push to server.

So now you can have your repo via http with SSL and nginx authentication.



Filed Under (Python) by Łukasz Balcerzak on November-9-2009

During the weekend I’ve created Djalog project hosted at the http://code.google.com/p/djalog/. It is simplest possible logging app aimed to work within Django context (or for prototyping as it is also logging-ready out of the box after import in any scripts).

I’ve also put it on the PyPi (http://pypi.python.org/pypi/Djalog) so in order to install it you would execute:

easy_install Djalog

and you are ready. If you want to quickly check how it works just type:

import djalog
import logging

logging.debug("Log some debug information.")
logging.info("Log some information.")
logging.warn("Log some warning.")
logging.error("Log some error.")
logging.critical("Log some critical information.")

from djalog import configure
configure(LOG_USE_COLORS=True, LOG_SQL=True, LOG_LEVEL=5)

logging.debug("Log some debug information.")
logging.info("Log some information.")
logging.warn("Log some warning.")
logging.error("Log some error.")
logging.critical("Log some critical information.")

# Log sql query
logging.sql("SELECT * FROM users WHERE username = 'admin'")

This is beta but it should be changed to “final” in two weeks. Remember that you may update projects from CheeseShop using “-U” option:

easy_install -U Djalog

Enjoy!



Filed Under (Python) by Łukasz Balcerzak on October-21-2009

While I love many things about SQLAlchemy this was something I just missed sooooo much – defining model’s methods without having to pass session object.
While using Django ORM for such action it is extra easy as there is no session objects at all (well, there is connection object but it’s much simpler and less sophisticated).
Assume you have BlogEntry and BlogComment mappers and you want to define function at entry model which returns related comments – I know, it is as simple as it could be, but it’s only an example.

class BlogEntry(Base):
    __tablename__ = 'blog_entry'

    title = Column(String)
    content = Column(Text)
    created_at = Column(DateTime, default=datetime.datetime.now)

    def __repr__(self):
        return self.title

class BlogComment(Base):
    __tablename__ = 'blog_comment'

    content = Column(Text)
    created_at = Column(DateTime, default=datetime.datetime.now)
    entry_id = Column(Integer, ForeignKey('blog_entry.id'))
    entry = relation('BlogEntry',
        primaryjoin='BlogEntry.id==BlogComment.entry_id',
        backref='comment_set')

You now can of course get comments using comment_set attribute on blog entry. But sometimes we want start querying for other objects, for some reasons.
With Django ORM, no problem, just define method on the model and start querying – it just works. With SQLAlchemy on the other hand we need to create query
using Session object. But how does mapper use proper session if you call ‘comment_set’? Well, I’ve found the answer here: http://www.sqlalchemy.org/docs/05/reference/orm/sessions.html . There is ‘Session.object_session’ class method which returns session object binded to an model object.

So now we can simply define method for BlogComment:

    def get_related_comments(self):
        session = Session.object_session(self)
        comment_list = session.query(BlogComment)\
            .filter(BlogComment.entry_id==BlogEntry.id)\
            .all()
        return comment_list

Just remember that object which is passed to ‘Session.object_session’ method has to be binded with some session first.



Filed Under (Python) by Marcin Kuźmiński on October-20-2009

I needed rot47 in python which is AFAIK not available so i made small function to implement rot47

def rot47(str):
    return ''.join([chr(33+((ord(c)-33+47)\
%(47*2))) if c!=" "else " " for c in str])

There is an rot13 implementation in python just encode a string using ‘rot13′ encoding

'string'.encode('rot13')


Filed Under (Python) by Łukasz Balcerzak on October-9-2009

Finally, I have released my second python project. It is small toolkit for browsing repositories (only svn is supported now) in simple way.
You can find it here: Version Control Browser.

A while ago I started to create django based, software management tracking project. I wanted to implement something similar to the browser from Trac. Long story, short – I’ve reorganized codes and ended up with needs of Django-independant repositories browsing library. There are some modules available right now but most of them focus on mirroring commit/update/pull/push commands – not on browsing which is much easier and should be more lightweight in my opinion.

If anyone who reads this would like to help me with the project – let me know.



Filed Under (Django, Pylons, SqlAlchemy) by Marcin Kuźmiński on September-26-2009

Recently i had to create a lot of models using declarative mode with sqlalchemy 0.5.5 It was very time consuming especially for large databases. I started to think about an automated solution.

Sqlalchemy have this auto load feature which fetches info about tables by itself. I wanted to use this somehow to generate a string which can be easily  copy/paste to database model definition script. So i started a little project to write auto  model generator for sql alchemy based on auto load feature in sqlalchemy.

The script  is not perfect but it works and save a huge amount of time just codding the models. In fact is was able to setup a 186 table database model in 15minutes with this script.

Well the script helped me a lot and now on when i have to load some new existing database or changes i use it all the time.

The documentation is inside the script i tried to write it so anybody could use it out of the box.

I tested it on 4 schema 200+ tables database and i worked quite good. This script still have to be polished but current functionality is enough for most users.

My script is going to be also a part of django-alchemy project started by my friend Lukasz Balcerzak. You can visit the project site @ http://code.google.com/p/django-alchemy/

I used it with Pylons application and Django with modded sqlalchemy. but it can be basically used in any app which uses sqlalchemy. I did not test it with mysql though,but it should work, just specify mysql as dialect.

You can download this script from sqlalchemy model generator



Filed Under (Python) by Marcin Kuźmiński on September-13-2009

I moved the blog to a new server. I think I’m going to move permanently from slicehost to hosteurope.de for the same price i have 1gb ram compared to 256 and 25 50 times the traffic. Also i compiled php 5.3 with php-fpm for this server, and updated mysql to newest available. I hope I’ll gain some performance with this as well. So enjoy a new theme and the server whitch i hope will be faster.



Filed Under (Editors) by Marcin Kuźmiński on September-6-2009

The creator of PyDev together with aptana released the version 1.5 of PyDev.This major release contains PyDev along with previously commercial non free PyDev extensions.
This is from now a Open Source project you could find on sourceforge
Pydev Extensions is a plugin that adds many other features to Pydev such as…

* code-analysis
* code completion with auto-import
* better implementation of go to definition
* remote debugging
* ‘quick-fixes’
* mark-occurrences <- this one is great :)

Before the PyDev extension was a paid plugin for aptana or eclipse.Now you could download it as PyDev 1.5 which is pyDev + pyDev extension merged together as a free open source project.
Great to here that :)

In order to install the pyDev 1.5 just update your eclipse repository to new update address which is http://pydev.org/updates

I think the nightly builds are yet not in 1.5 so I’ll use this repo for now.

Also i found a great link for PyDev functionality.

http://pydev.org/manual_adv_features.html

i did not know eclipse provide the ctrl+/ functionality (text auto completion emacs style…) This one is very handy !!

Enjoy new even better pyDev