Skip to content

Instantly share code, notes, and snippets.

@Giancarlos
Forked from jaraco/foo.py
Created November 15, 2018 12:29
Show Gist options
  • Save Giancarlos/e078f6c6bd8fe949caac8ef5cf37d92b to your computer and use it in GitHub Desktop.
Save Giancarlos/e078f6c6bd8fe949caac8ef5cf37d92b to your computer and use it in GitHub Desktop.
import functools
import collections
import cherrypy
__metaclass__ = type # enable new-style classes by default
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