Skip to content

Instantly share code, notes, and snippets.

@omaraboumrad omaraboumrad/
Last active Jan 2, 2016

What would you like to do?
http url router
from toll import run, Toll
app = Toll(__name__)
def index():
return 'Hello World'
def showme(num):
return 'You have posted {}'.format(num), {'Content-Type': 'text/html'}
run('', 8000, app)
import re
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
class NoRouteFoundException(Exception):
class Toll(object):
def __init__(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):
_headers_to_update = {'Content-type': 'text/plain'}
_headers = {}
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'
res(status, _headers.items())
return result
def run(host, port, app):
httpd = make_server(host, port, app.accept)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.