web developer & system programmer

coder . cl

ramblings and thoughts on programming...


minimal design patterns in django

published: 11-06-2011 / updated: 11-06-2011
posted in: development, programming, python, tips
by Daniel Molina Wegener

Using design patterns to encapsulate application logic is very cool, only when you do not over-architect your application. Any excessive usage of design patterns and architectural patterns can lead you to oversized applications. Applying design patterns correctly can allow you to get a well defined architecture and a well designed application. You must remember that Django do not uses the MVC pattern, instead — as they development team describes it — Django is MTV: “Model, Template and View”. So, I will try to explain an implementation of the PAC architectural pattern driven under Django to allow you to implement scalable Django applications.

The “Presentation, Abstraction, Control” pattern is an architectural pattern where the presentation imports an abstraction layer to the Control and uses it, emulating the Control itself. So, on the PAC pattern, some design patterns like Façade, Delegate, Adapter and similar ones, are mandatory to abstract the Control layer. On the MTV pattern used by Django, it can be visualized as follows.

Django MTV Pattern plus PAC

Django MTV Pattern plus PAC

On the diagram above, we meet the MTV pattern, and we add the PAC layer in the middle of the View and the Model. Why to do that?, even if our application uses only one data store, for example a relational one, like MySQL, we should provide an Abstraction layer to access it, also a Control to encapsulate application logic inside the Control, instead of using the model directly and we use the abstraction layer on to hide the original source. On any application, even when those applications are scaling, we tend to use more than one data store, for example when we migrate some logic to Redis to make some transactions faster and asynchronous.

So, we preserve the original Django structure on MTV, using Django templates or JSON Views when are required, the View itself to control which data will be displayed and to process user or client input, and we hide the application logic behind the Abstraction layer, use concentrate the application logic on the Control layer and we use the Model only as Data Store.

We should use an Adapter pattern to abstract the data source. For example for the following decorators will convert from the View plain dictionaries to Model objects and from the Model to plain dictionaries to be used on the View.


def import_to_model(model, arg = None):
    """
    Imports the returning argument to the model and
    uses its model instance as input for the wrapped
    function.
    """
    def outer(f):
        @wraps(f)
        def inner_view(inst, *args, **kwargs):
            try:
                n = model()
                if arg in kwargs:
                    for k in kwargs[arg]:
                        setattr(n, k, kwargs[arg])
                    return f(inst, n, **kwargs)
                else:
                    for k in args[0].keys():
                        setattr(n, k, args[0][k])
                    return f(inst, n, **kwargs)
            except Exception, e:
                l.error(e)
                return False
        return inner_view
    return outer

def export_from_model():
    """
    Exports the resulting instance as dictionary for to be
    used as serializable object.
    """
    def outer(f):
        @wraps(f)
        def inner_view(ci, *args, **kwargs):
            try:
                input_obj = f(ci, *args, **kwargs)
                n = dict()
                for k in input_obj.__dict__.keys():
                    if not k.startswith('__') and not k.endswith('__') and k != '_state':
                        n[k] = getattr(input_obj, k)
                return n
            except Exception, e:
                l.error(e)
                return False
        return inner_view
    return outer

We can use those decorators to make object conversion between layers automatically. So, a simple architecture, with very low layers. This model is quite simple, not over-architected, and probably it can ensure that you will work with the proper abstraction layer without over-sizing the application. Remember to keep the things simple as you can.

Design Patterns to be Used

Design Patterns to be Used

The scope of this model is a minimal, but efficient abstraction layer. For example if we migrate our application from Django to Google App Engine, the application probably will be easier to export to GAE, without rewriting too much code, because it is very well encapsulated and well organized. So we can create the proper modules and namespaces to put the application logic on the proper layer. For example we can consume a JSON service from the Control, which is not a Model, and it will be properly encapsulated behind the abstraction layer, leaving the minimal logic on the View, just to process the data that will be used on the Presentation.

You can extend or reduce this application model to fit your needs. I hope that you will like the usage of the PAC pattern present here. Enjoy deploying Django applications.


No coments yet.

post a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>