Skip to content

Instantly share code, notes, and snippets.

@mcdonc
Created October 8, 2011 17:13
Show Gist options
  • Save mcdonc/1272572 to your computer and use it in GitHub Desktop.
Save mcdonc/1272572 to your computer and use it in GitHub Desktop.
rev2 of api demo
# framework
from pyramid.view import view_config
import venusian
class api(object):
def __init__(self, **kw):
self.route_pattern = kw.pop('pattern')
self.route_method = kw.pop('method', None)
self.kw = kw
def __call__(self, func):
kw = self.kw.copy()
docstring = func.__doc__
def callback(context, name, ob):
config = context.config.with_package(info.module)
renderer = self.kw.get('renderer')
route_name = func.__name__
route_method = self.route_method
config.add_apidoc((self.route_pattern, route_method),
docstring, renderer)
config.add_route(route_name, self.route_pattern,
request_method=route_method)
config.add_view(view=ob, route_name=route_name, **kw)
info = venusian.attach(func, callback, category='pyramid')
if info.scope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' into the settings if one isn't already in there
if kw['attr'] is None:
kw['attr'] = func.__name__
kw['_info'] = info.codeinfo # fbo "action_method"
return func
def add_apidoc(config, pattern, docstring, renderer):
apidocs = config.registry.settings.setdefault('apidocs', {})
info = apidocs.setdefault(pattern, {})
info['docstring'] = docstring
info['renderer'] = renderer
@view_config(route_name='apidocs', renderer='string')
def apidocs(request):
L = []
for k, v in request.registry.settings['apidocs'].items():
L.append('%s: %s' % (k, v))
return '\n\n'.join(L)
# app code
@api(pattern='/username/{id}', renderer='json', method='GET')
def username_get(request):
""" Returns 1 if the username is in use, 0 if it is unavailable. The
answer is in plain text.
Possible errors:
- 503: there was an error getting the information
"""
return 'get %s' % request.matchdict['id']
@api(pattern='/username/{id}', renderer='json', method='DELETE')
def username_del(request):
""" Deletes the userid named {id}. Returns 1 if the username was in use,
0 if it was unavailable. The answer is in plain text.
Possible errors:
- 503: there was an error getting the information
"""
return 'del %s' % request.matchdict['id']
if __name__ == '__main__':
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
config = Configurator()
config.add_directive('add_apidoc', add_apidoc)
config.add_route('username', '/username')
config.add_route('apidocs', '/apidocs')
config.scan()
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment