Skip to content

Instantly share code, notes, and snippets.

@husio
Created February 1, 2013 14:14
Show Gist options
  • Save husio/4691536 to your computer and use it in GitHub Desktop.
Save husio/4691536 to your computer and use it in GitHub Desktop.
few lines of python + webob to make a real microframework ;)
import collections
import re
from wsgiref import simple_server
from webob import Request, Response
class App:
def __init__(self):
self.routes = collections.defaultdict(list)
def as_wsgi_handler(self):
def handler(environ, start_response):
request = Request(environ)
view, kwargs = self._view_for(request.method, request.path_info)
if not view:
raise Exception(404)
response = view(request, **kwargs)
if isinstance(response, str):
response = Response(response)
return response(environ, start_response)
return handler
def route(self, path, *methods):
def decorator(view):
rx = re.compile(path)
for method in methods:
self.routes[method].append((rx, view))
return view
return decorator
def _view_for(self, method, path):
for rx, view in self.routes[method]:
match = rx.match(path)
if match:
kwargs = match.groupdict()
return view, kwargs
def serve(app, host='localhost', port=8000):
server = simple_server.make_server(host, port, app.as_wsgi_handler())
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment