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
software engineering
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)
Thanks for the advice, I’ll do that.