Login

View dispatch based on HTTP verb

Author:
malcolmt
Posted:
October 6, 2007
Language:
Python
Version:
.96
Score:
4 (after 4 ratings)

Sometimes, when views are particularly complex, it's useful to send the different request methods to different functions. If you have to do this frequently, the repetition gets tiring. This helper class can be used to simplify that.

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
Helper utility for passing control to different views based on the HTTP method.

Construct instances of this class with a dictionary mapping method names (or
sequence of method names) to the view function that will handle them. The
special and optional '__default__' key is used to handle all otherwise
unmentioned methods. Methods not mentioned in the dictionary are implicitly
forbidden if there is no '__default__' key.

For example:

    dispatch_dict = {
        ('POST', 'PUT') : new_data_handler,
        'GET': display_only_handler
    }

    urlconf = patterns('',
        url('/my/pattern/', MethodDispatcher(dispatch_dict))
    )

Each view function in the dictionary will be passed the same set of arguments,
so be prepared to use *args and/or **kwargs if you need to make the function
signatures uniform.
"""
from django import http

class MethodDispatcher(object):
    def __init__(self, method_map):
        self.methods = {}
        self.default = None
        for key, value in method_map.items():
            if key == '__default__':
                self.default = value
            elif isinstance(key, basestring):
                self.methods[key] = value
            else:
                for elt in key:
                    self.methods[elt] = value

    def __call__(self, request, *args, **kwargs):
        view_func = self.methods.get(request.method, self.default)
        if view_func:
            return view_func(request, *args, **kwargs)
        return http.HttpResponseNotAllowed(self.methods.keys())

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.