Skip to content

Instantly share code, notes, and snippets.

@jaraco
Last active November 15, 2018 12:29
Show Gist options
  • Save jaraco/a447f185a3e088d1f24983e6efd21cef to your computer and use it in GitHub Desktop.
Save jaraco/a447f185a3e088d1f24983e6efd21cef 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")
"""
__isabstractmethod__ = False
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