Tiago Cogumbreiro

O Irrepupável

Back to top

Showing posts with label django. Show all posts
Showing posts with label django. Show all posts

Friday, May 30, 2008

Simple Django handlers

Or, an example about introspection targeting Python's functions.

I really like the way CherryPy maps GET parameters to the parameters of the handling function (usually, methods). I miss this mapping in Django, therefore I implemented it. I am "lazy" and I did not search Django's API for something related to this — I did this for pleasure.

Anyway, I have implemented a decorator, params_from_GET that adds this functionality to Django-handlers. You have to read the docstring to read the usage.

Code dump (licensed under public domain):

import inspect
def get_func_args(func):
    """
    Returns a generators of pairs (parameter name, default value)
    of the target function.
    """
    (args, varargs, varkw, defaults) = inspect.getargspec(func)
    if defaults is None:
        defaults = ()
    offset = len(args) - len(defaults)
    return args[:offset], dict(zip(args[offset:], defaults))

def params_from(func, method, default_value=''):
    """
    Returns a decorator, see params_from_GET.
    """
    # get the default params
    args, params = get_func_args(func)
    if args[0] != "request":
        raise TypeError("First parameters needs to be 'request'")
    for param in args[1:]:
        params[param] = default_value=''
    
    def wrapper(request, **orig_kwargs):
        # copy the parameters
        kwargs = params.copy()
        # get the map for the defined method, e.g GET
        method_dict = getattr(request, method)
        # set the request object
        kwargs['request'] = request
        for key in params:
            # fill with values that were sent by the user
            if key in method_dict:
                kwargs[key] = method_dict[key]
        kwargs.update(orig_kwargs)
        return func(**kwargs)
    return wrapper

def params_from_GET(func):
    """
    The decorator pics up a handler function and fetches the
    values from the GET map.

    For example:

    @params_from_GET
    handler(request, foo, bar):
       pass

    Is the same as:

    handler(request):
       foo = request.GET('foo', '')
       bar = request.GET('bar', '')
    """
    return params_from(func, 'GET')

Update: added support for the keyword arguments that may be passed to the dispatcher by urls.py.

Saturday, March 29, 2008

Django and Unicode

I have made this patch against Django SVN r7379, please have a look at it:

--- /usr/lib/python2.5/site-packages/django/http/__init__.py    2008-03-29 22:24:02.000000000 +0000
+++ __init__.py 2008-03-29 22:23:03.000000000 +0000
@@ -360,10 +360,8 @@
         return self
 
     def next(self):
-        chunk = self._iterator.next()
-        if isinstance(chunk, unicode):
-            chunk = chunk.encode(self._charset)
-        return str(chunk)
+        chunk = unicode(self._iterator.next())
+        return chunk.encode(self._charset)
 
     def close(self):
         if hasattr(self._container, 'close'):

Before the patch, a chunk (the reply that will be sent by the HTTP server to the client) is encoded with the charset defined in our project (self._charset) only if it is an unicode object, otherwise, it will happily convert to a string using the system's encoding (by using the function str), which was resulting in a UnicodeEncodeError exception that would break Django.

If you want to make sure that the reply you are sending, through your HTTPResponse, is encoded into a string using the project's encoding, then convert it first into a unicode object. If my patch is accepted, though, this will be done automatically for you.

Oh, by the way, I am enjoying Django. I am using it to create REST web-services. It is being an enjoying and out-of-your-face experience.

Thursday, November 02, 2006

Link Flood, Part 1

Um novo e interessante projecto que surgiu é o Nouveau, trata-se de uma implementação livre de drivers para placas gráficas NVidia. Tem por base o módulo do X nv e usa o programa REnouveau para, através de engenharia reversa, descobrir como a implementação proprietária funciona. Será que vamos ter umas drivers de qualidade Open Source?

Também relativo ao mundo Open Source, o projecto Django está a criar um livro, The Django Book. O contributo da comunidade é promovido através do sítio interessante onde se podem adicionar comentários, com a granularidade ao parágrafo.

O sítio NZone, da NVidia, está a disponibilizar uma demo do Cedega. Este parece um sinal que este sistema operativo o sistema operativo onde este programa corre começa a ter mais visibilidade (se bem que ínfima ainda) no mundo dos jogadores.

Uma gama de portáteis muito atraente é a Levio da marca Transtec. São muito bonitos, leves, bem artilhados, vêm com Linux e, por incrível que pareça, são baratos!