Django RESTful resources

Last year I blogged about a neat trick in Django to have multiple views per HTTP verb. Since then I’ve been playing with RESTful applications and decided to see if there was a nicer way to expose “resources” in Django. The following is what I’ve come up with so far. Listing: router.py from django.http import Http404, HttpResponseNotAllowed def get_handler_method(request_handler, http_method): try: handler_method = getattr(request_handler, http_method.lower()) if callable(handler_method): return handler_method except AttributeError: pass class Resource: http_methods = ['GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'] @classmethod def dispatch(cls, request, *args, **kwargs): request_handler = cls() if request....

Django and multiple methods per url pattern

HTTP verbs are not used to determine the route to a view method by deliberate design in Django. Sometimes I find it useful to be able to specify different methods for the same url pattern - one per HTTP verb. The Django book contains an interesting example of how this can be done using the django.conf.urls.defaults.url method to separate POST from GET processing. I’ve extended the example to provide handling to cover the standard HTTP verbs....