Created
October 7, 2011 15:11
-
-
Save mcdonc/1270482 to your computer and use it in GitHub Desktop.
apidoc messing around
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# framework | |
from pyramid.view import view_config | |
from pyramid.interfaces import IRoutesMapper | |
class api(view_config): | |
def __init__(self, **kw): | |
view_config.__init__(self, **kw) | |
def __call__(self, func): | |
view_config.__call__(self, func) | |
docstring = func.__doc__ | |
def callback(context, name, ob): | |
config = context.config | |
renderer = self.renderer | |
route_name = self.route_name | |
config.add_apidoc(route_name, docstring, renderer) | |
self.venusian.attach(func, callback, category='pyramid') | |
return func | |
def add_apidoc(config, url, docstring, renderer): | |
apidocs = config.registry.settings.setdefault('apidocs', {}) | |
info = apidocs.setdefault(url, {}) | |
info['docstring'] = docstring | |
info['renderer'] = renderer | |
@view_config(route_name='apidocs', renderer='string') | |
def apidocs(request): | |
L = [] | |
mapper = request.registry.getUtility(IRoutesMapper) | |
for k, v in request.registry.settings['apidocs'].items(): | |
route = mapper.get_route(k) | |
if route is not None: | |
L.append('%s: %s' % (route.pattern, v)) | |
return '\n\n'.join(L) | |
# app code | |
@api(route_name='username', renderer='json') | |
def username(self): | |
""" 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 1 | |
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