Skip to content

Instantly share code, notes, and snippets.

@jaraco
Created December 12, 2017 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaraco/d60ed19473696919a6664faf7032525b to your computer and use it in GitHub Desktop.
Save jaraco/d60ed19473696919a6664faf7032525b to your computer and use it in GitHub Desktop.
import functools
import collections
import cherrypy
class SelectedMethod:
"""
Descriptor allowing a series of handler methods to satisfy
a variety of behaviors based on the request method.
Works similar to the MethodDispatcher, but doesn't
require replacing the whole dispatch mechanism, so
may be deployed selectively.
First, decorate your method using SelectedMethod::
class App:
@SelectedMethod
def index(self):
return "Hello World"
Then, add separate handlers for specific methods::
@index.GET
def get(self):
return "Your method was GET"
@index.POST
def delete(self):
db.delete(self.id)
The first handler passed will always handle any methods
not specified. The app may wish to
raise 405 in this case::
@SelectedMethod
def index(self):
raise cherrypy.HTTPError("405 Method Not Allowed")
"""
def __init__(self, orig):
self.methods = collections.defaultdict(lambda: orig)
def __get__(self, obj, type=None):
method = self.methods[cherrypy.request.method]
bound = functools.partial(method, obj)
bound.exposed = True
return bound
def __getattr__(self, method):
"""
Return a decorator suitable for wrapping another
"""
def wrapper(func):
self.methods[method] = func
return func
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment