Last active
January 2, 2016 08:18
-
-
Save omaraboumrad/767f2545ff6e36a7ed2e to your computer and use it in GitHub Desktop.
http url router
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
from toll import run, Toll | |
app = Toll(__name__) | |
@app.route(r'^/$') | |
def index(): | |
return 'Hello World' | |
@app.route(r'^/(\d+)/$') | |
def showme(num): | |
return 'You have posted {}'.format(num), {'Content-Type': 'text/html'} | |
run('127.0.0.1', 8000, app) |
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 re | |
from wsgiref.util import setup_testing_defaults | |
from wsgiref.simple_server import make_server | |
class NoRouteFoundException(Exception): | |
pass | |
class Toll(object): | |
def __init__(self, name): | |
self.name = name | |
self.routes = {} | |
def route(self, pattern): | |
def to(action): | |
self.routes[pattern] = action | |
return action | |
return to | |
def handle_route(self, path): | |
for route, _func in self.routes.items(): | |
m = re.match(route, path) | |
if m: | |
# TODO: also set request kwargs somewhere | |
# groupdict = m.groupdict() | |
return _func(*m.groups()) | |
raise NoRouteFoundException('No route found') | |
def accept(self, environ, res): | |
setup_testing_defaults(environ) | |
_headers_to_update = {'Content-type': 'text/plain'} | |
_headers = {} | |
try: | |
status = '200 OK' | |
result = self.handle_route(environ['PATH_INFO']) | |
# would be nice to get rid of this condition | |
if type(result) is tuple and len(result) == 2: | |
result, _headers = result | |
except NoRouteFoundException: | |
status = '404 Not Found' | |
result = 'ERROR: Not Found' | |
_headers_to_update.update(_headers) | |
res(status, _headers.items()) | |
return result | |
def run(host, port, app): | |
httpd = make_server(host, port, app.accept) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment