Skip to content

Instantly share code, notes, and snippets.

@arsatiki
Created August 13, 2009 09:00
Show Gist options
  • Save arsatiki/167057 to your computer and use it in GitHub Desktop.
Save arsatiki/167057 to your computer and use it in GitHub Desktop.
# HTTP view decorators inspired by property.setter
# See also a class-based solution in http://gist.github.com/85410
class MethodDispatcher(object):
def __init__(self):
self.views = {}
def __call__(self, request, *args, **kwargs):
m = request.method.upper()
if m in self.views:
return self.views[m](request, *args, **kwargs)
if None in self.views:
return self.views[None](request, *args, **kwargs)
return HTTPNotAllowed()
def methods(self, *ms):
ms = [m.upper() for m in ms] if ms else [None]
def decorator(func):
for m in ms:
self.views[m] = func
return self
return decorator
def http_methods(*methods):
"A wrapper for building the method dispatcher object"
def decorator(func):
dispatcher = MethodDispatcher()
dispatcher.methods(methods)
return dispatcher
return decorator
# An example
@http_methods("get", "post")
def index(request):
# This view sees only requests whose methods are GET or POST
@index.methods("delete")
def index(request):
# This view responds to DELETE
@index.methods()
def index(request):
# Empty argument means that everything goes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment