Created
February 1, 2013 14:14
-
-
Save husio/4691536 to your computer and use it in GitHub Desktop.
few lines of python + webob to make a real microframework ;)
This file contains 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
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