View dispatch based on HTTP verb

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.

"""Helper utility for passing control to different views based on the HTTP method.Construct instances of this class with a dictionary mapping method names (orsequence of method names) to the view function that will handle them. Thespecial and optional '__default__' key is used to handle all otherwiseunmentioned methods. Methods not mentioned in the dictionary are implicitlyforbidden 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 functionsignatures uniform."""fromdjangoimporthttpclassMethodDispatcher(object):def__init__(self,method_map):self.methods={}self.default=Noneforkey,valueinmethod_map.items():ifkey=='__default__':self.default=valueelifisinstance(key,basestring):self.methods[key]=valueelse:foreltinkey:self.methods[elt]=valuedef__call__(self,request,*args,**kwargs):view_func=self.methods.get(request.method,self.default)ifview_func:returnview_func(request,*args,**kwargs)returnhttp.HttpResponseNotAllowed(self.methods.keys())