Skip to content

Instantly share code, notes, and snippets.

@btubbs
Created February 4, 2015 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btubbs/92010354170044faf11a to your computer and use it in GitHub Desktop.
Save btubbs/92010354170044faf11a to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
webzeug.py
Adapted from Armin Ronacher's "webpylike".
See https://github.com/mitsuhiko/werkzeug/blob/master/examples/webpylike/webpylike.py
With this, an application can look like this:
from webzeug import App, Request, Response, View
class Index(View):
def GET(self):
return Response('Hello World')
class Hello(View):
def GET(self, name):
return Response('Hey there ' + name + '!')
app = App([
('/', 'index', Index),
('/people/<name>/', 'hello', Hello),
])
if __name__ == "__main__":
from werkzeug.serving import run_simple
run_simple('0.0.0.0', 8000, app)
"""
from werkzeug.routing import Map, Rule
from werkzeug.wrappers import BaseRequest, BaseResponse
from werkzeug.exceptions import HTTPException, MethodNotAllowed, \
NotImplemented, NotFound
class Request(BaseRequest):
"""Encapsulates a request."""
class Response(BaseResponse):
"""Encapsulates a response."""
class View(object):
"""Baseclass for our views."""
def __init__(self, app, req):
self.app = app
self.req = req
def GET(self):
raise MethodNotAllowed()
POST = DELETE = PUT = GET
def HEAD(self):
return self.GET()
class App(object):
def __init__(self, urls):
self.urls = urls
self.handlers = {}
self.rules = []
for pat, name, func in urls:
self.rules.append(Rule(pat, endpoint=name))
self.handlers[name] = func
self.map = Map(self.rules)
def __call__(self, environ, start_response):
try:
req = Request(environ)
adapter = self.map.bind_to_environ(environ)
view_name, params = adapter.match()
view_cls = self.handlers[view_name]
view = view_cls(self, req)
if req.method not in ('GET', 'HEAD', 'POST',
'DELETE', 'PUT'):
raise NotImplemented()
resp = getattr(view, req.method)(**params)
except HTTPException, e:
resp = e
return resp(environ, start_response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment