Home > Research, School > Django URL Dispatcher

Django URL Dispatcher

Django has a nifty url dispatcher which allows you to direct requests from a url to an event handler in the form of a callable object in python.  If you followed the tutorials, your code is now probably littered with functions.   You can also use classes for event handling as follows.

from django.http import HttpResponse
from django.template import Context, loader
from scibrowser.web.widgets.form import FileLoader
from scibrowser.resources.fixtures import gdf
from scibrowser.lib.parsing.gdf import GDF

class Handler(object):
    def __init__(self, template=None):
        self.template = loader.get_template(template)

    def __call__(self, request, **kwargs):
        handler = getattr(self, "event_%s" %request.method.lower(), None)
        return HttpResponse(self.template.render(Context(handler(request))))

class GraphHandler(Handler):
    def __init__(self, template=None):
        self.file = gdf
        self.form = FileLoader()
        super(GraphHandler, self).__init__(template)

    def event_get(self, request):
        return {'javascript': GDF().json(self.file), 'form': self.form}

    def event_post(self, request):
        self.form = FileLoader(request.POST, request.FILES)
        file = gdf
        if self.form.is_valid():
            file = request.FILES['file'].read()
        return {'javascript': GDF().json(self.file), 'form': self.form}

Then, in the urls file you can have the dispatcher call the handler as follows:

from django.conf.urls.defaults import patterns, url
from scibrowser.web.graph.views import GraphHandler

urlpatterns = patterns('web.graph.views',
    # Example:
    url(r'^$', GraphHandler(template='graph.html')),
    url(r'^fd/$', GraphHandler(template='fdgraph.html')),
Categories: Research, School Tags:
  1. July 3, 2010 at 6:06 am

    You should probably add a prefix to the request method, both for clarity, and to avoid the possibility of invoking some unexpected method if the request method ends up being something unexpected. (I don’t know Django, so I’m not sure if it’s possible to send a method of ‘__init__’ or something crazy like that)

    • nim
      July 3, 2010 at 6:50 am

      Thanks for the advice, I’ll do that.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: