View dispatch based on HTTP verb

 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. RestView - class for creating a view that dispatches based on request.method by simon 5 years, 7 months ago
  2. Convenient class based views by eallik 3 years, 10 months ago
  3. simple text image view by derelm 7 years, 1 month ago
  4. PropertyBasedContext by a4tunado 2 years, 9 months ago
  5. ForeignKey dropdown selector by rubic 7 years, 1 month ago

Comments

(Forgotten your password?)