Archive

Archive for July, 2010

Django URL Dispatcher

July 2, 2010 2 comments

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: