Login

Simple views dispatcher by http methods

Author:
kmerenkov
Posted:
November 16, 2009
Language:
Python
Version:
1.1
Tags:
urls rest http url
Score:
2 (after 2 ratings)

Calls a view by request.method value.

To use this dispatcher write your urls.py like this:

urlpatterns = pattern('',
    url(r'^foo/$', dispatch(head=callable1,
                            get=callable2,
                            delete=callable3)),
)

If request.method is equal to head, callable1 will be called as your usual view function; if it is get, callable2 will be called; et cetera. If the method specified in request.method is not one handled by dispatch(..), HttpResponseNotAllowed is returned.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.http import HttpResponseNotAllowed


def dispatch(**methods):
    """Calls a view by request.method value.

    To use this dispatcher write your urls.py like this:

    urlpatterns = pattern('',
        url(r'^foo/$', dispatch(head=callable1,
                                get=callable2,
                                delete=callable3)),
    )

    If request.method is equal to head, callable1 will be called as your usual view function;
    if it is "get", callable2 will be called; et cetera.
    If the method specified in request.method is not one handled by dispatch(..),
    HttpResponseNotAllowed is returned.
    """

    lc_methods = dict( (method.lower(), handler) for (method, handler) in methods.iteritems() )

    def __dispatch(request, *args, **kwargs):
        handler = lc_methods.get(request.method.lower())
        if handler:
            return handler(request, *args, **kwargs)
        else:
            return HttpResponseNotAllowed(m.upper() for m in lc_methods.keys())
    return __dispatch

More like this

  1. RestView - class for creating a view that dispatches based on request.method by simon 6 years, 11 months ago
  2. Base class for RESTful Views by jpwatts 6 years, 9 months ago
  3. Generic AJAX app by Rupe 6 years, 2 months ago
  4. Using class methods as views by panyam 6 years, 2 months ago
  5. View dispatch based on HTTP verb by malcolmt 7 years, 11 months ago

Comments

schinckel (on November 16, 2009):

I really like this. It always bothered me (with RESTful stuff, anyway) how the one handler does GET and PUT, etc.

#

Please login first before commenting.