Skip to content

Instantly share code, notes, and snippets.

@mmerickel
Created April 1, 2013 16: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 mmerickel/5286023 to your computer and use it in GitHub Desktop.
Save mmerickel/5286023 to your computer and use it in GitHub Desktop.
poor man's rest resource in pyramid
class rest_resource(object):
all_methods = frozenset([
'head', 'get', 'post', 'put', 'patch', 'delete'])
def __init__(self, **kw):
self.kw = kw # view defaults
def __call__(self, wrapped):
# grab the supported methods from the class
methods = self.all_methods.intersection(set(vars(wrapped).keys()))
if 'get' in methods:
methods.add('head')
missing_methods = [m.upper() for m in self.all_methods - methods]
allow = ['OPTIONS'] + list(missing_methods)
def options(request):
resp = request.response
resp.allow = allow
return resp
def not_allowed(request):
resp = request.response
resp.allow = allow
resp.status = 405
return resp
def callback(context, name, obj):
config = context.config.with_package(info.module)
# register all methods
for method in methods:
attr = method
# redirect head requests to get
# unless an explicit head method exists
if method == 'head':
if not hasattr(wrapped, attr):
attr = 'get'
config.add_view(
wrapped,
attr=attr,
request_method=method.upper(),
**self.kw)
# catch OPTIONS requests
config.add_view(
options,
route_name=self.route_name,
request_method='OPTIONS',
**self.kw)
# catch requests to unsupported methods to raise a 405
# but allow other views to propagate to global notfound view
config.add_view(
not_allowed,
route_name=self.route_name,
context=HTTPNotFound,
request_method=missing_methods,
**self.kw)
info = venusian.attach(wrapped, callback, category='pyramid')
return wrapped
@rest_resource(route_name='root')
class Root(object):
def __init__(self, request):
self.request = request
def get(self):
return Response('GET request')
def post(self):
return Response('POST request')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment