Perform extra work after rendering a view

At times, you need to perform some postprocessing after a view has been rendered. It could be some serious work, in which case you’d better arrange for it to be carried over by a separate thread, a separate process or even a separate server, or it could be just a quick update of the database. In either case, you need to ensure that whatever has to be done does not influence the response.

Of course, in a manually  implemented view, rendering to the response need not be the last action. You can always write:

def my_view(request):
    do_some_work()
    response = render_to_response('my_view.html')
    do_extra_work()
    return response

But, when using a class-based generic view, you might be left wondering for a while, especially if you happen to focus too much on the wrong part of the documentation.

Turns out that the answer is quite simple and elegant. Class-based generic views return a new kind of response introduced in Django 1.3, the TemplateResponse, which provides a hook to perform extra work after the template has been rendered. Armed with that knowledge, you can easily write a generic mixin like this:

class PostprocessorMixin(object):
    def get(*args, **kwargs):
        resp = super(PostprocessorMixin, self).get(*args, **kwargs)
        resp.add_post_render_callback(self.postprocess)
        return resp

When you later need to perform extra work after rendering the response, mix this in your custom derived views and implement your postprocessing in postprocess.

In real life, tawmas goes by the name of Tommaso R. Donnarumma. When asked, he describes himself as an Italian in Québec; a passionate programmer who has also been a project manager and a sysadmin; an Ubuntu user; an avid photographer; a lover of books, Baroque music, jazz, red wines, white beers; a gamer; an incurable curious.

Leave a Reply

Your email address will not be published. Required fields are marked *