Python Snippet: Converting a complex object to json


Here’s a simple recipe, to convert most Python class-objects to json and back.

Here’s the setup:

import json

class Foo:
    def __init__(self, name, values): = name
        self.values = values

Converting to json:

an_object = Foo('John', (123, 456, 789))

json_string = json.dumps(vars(an_object))

Quite simple, isn’t it? Using the vars function, Python converts the object to a dictionary which can then be jsonified, using the json.dums function.

The reverse is quite simple as well:

a_fresh_object = Foo(**json.loads(json_string))

This simply takes the output of json.loads, which is a dict, and maps the keys and values of that dict to the names arguments of Foo’s __init__ method.


So long…

Writing Python Function Decorators

Python has a pretty neat way, of letting you write function decorators.

A Function decorator in general, alters or appends to the functionality performed by the decorated method, without having to directly depend on or know it.

Thus it is possible, to use decorators to declare aspects, without re-writing the same code over and over again.

In python, you can decorate a function by using the following syntax:

def my_function(arg1, arg2):
    print "Something with %s and %s" % (arg1, arg2)

By doing that, python exchanges any calls to your method, by calls to the decorator, defined as my_decorator. This decorator can now decide, to do some additional work and (if wanted) call the original function.

To define a decorator, you have to write a function factory. That is a function, that defines and returns another function, that can be called with the original function as an argument.

def my_decorator(argument):
    def outer_wrapper(original_method):
        # This code gets called, when the decorated
        # function gets defined

        def inner_wrapper(*args, **kwargs):
            # This method gets called, instead of the
            # actual function call to the decorated
            # function.
            print "I come from before the function"
            return_value = original_method(args, kwargs)
            print "The method returned %s" % return_value
            return return_value

        return inner_wrapper
    return outer_wrapper

Have fun.

A Block of Modern Flats in Django

I have tried my hand a bit at using Django the last weeks and it is a web framework, that really is fun to develop in.

However there is one thing that I came to fight with quite a bit. That is building a good multi-tenant aware application in django.

It is to be said, that I wanted a true multi-tenant application, that could serve different data universes from the same running server and the same database, which is a focus that django simply hadn’t been build for yet. Nevertheless, since it is a very transparent and straight forward framework, I actually got it to work quite nicely.
Continue reading