Difference between revisions of "User:Babbage Linden/Django/Dispatch"

From Second Life Wiki
Jump to navigation Jump to search
(New page: By default, Django doesn't provide a way to demultiplex requests based on HTTP methods, but this snippet provides that functionality and is based on examples from [http://www.djangosnippet...)
 
(No difference)

Latest revision as of 08:45, 2 December 2008

By default, Django doesn't provide a way to demultiplex requests based on HTTP methods, but this snippet provides that functionality and is based on examples from djangosnippets.org and RESTful Web Services.

from django.http import HttpResponseNotAllowed

class HttpMethodDispatcher(object):
    def __init__(self, module_name, prefix):
        self.module = __import__(module_name)
        module_names = module_name.split('.')
        for module_name in module_names[1:]:
            self.module = getattr(self.module, module_name)
        self.prefix = '%s_' % prefix

    def __call__(self, request, **kwargs):
        try:
            func = getattr(self.module, '%s%s' % (self.prefix,request.method))
        except AttributeError:
            allowed_methods = [func.lstrip(self.prefix)
                               for func in dir(self.module)
                               if func.startswith(self.prefix)]
            return HttpResponseNotAllowed(allowed_methods)
        return func(request, **kwargs)

The dispatcher can be used in the URL configuration like this:

region_dispatcher = HttpMethodDispatcher('presence.rest', 'region')

urlpatterns = patterns('',
    # ...
    (r'^region/(?P<region_id>%s)/$' % uuid, region_dispatcher),
    # ...
)