Skip to content

Instantly share code, notes, and snippets.

@aodag
Created August 27, 2011 06:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aodag/1175051 to your computer and use it in GitHub Desktop.
Save aodag/1175051 to your computer and use it in GitHub Desktop.
Greeting message wsgi application with various wsgi components
import os
import formencode
from formencode import validators
from formencode import htmlfill
from routes import Mapper
from mako.lookup import TemplateLookup
from webob import Response
from webob.exc import HTTPNotFound, HTTPFound
from webob.dec import wsgify
here = os.path.dirname(__file__)
templates = TemplateLookup(directories=[os.path.join(here, 'templates')])
class Dispatcher(object):
def __init__(self):
self.mapper = Mapper()
self.controllers = {}
def add_route(self, route_name, pattern, controller):
self.mapper.connect(route_name, pattern)
self.controllers[route_name] = controller
@wsgify
def __call__(self, request):
matched = self.mapper.routematch(request.path_info, request.method)
if not matched:
raise HTTPNotFound
matchdict, route = matched
if route.name not in self.controllers:
raise HTTPNotFound
request.routes = self.mapper._routenames
return self.controllers[route.name](request)
class HelloSchema(formencode.Schema):
name = validators.UnicodeString(not_empty=True)
def index(request):
tmpl = templates.get_template('index.mak')
return Response(tmpl.render(request=request))
def hello(request):
try:
params = HelloSchema.to_python(request.params)
except formencode.Invalid, e:
res = index(request)
res.text = htmlfill.render(res.body, request.params, errors=e.error_dict)
return res
tmpl = templates.get_template('hello.mak')
return Response(tmpl.render(name=params['name']))
application = Dispatcher()
application.add_route('index', '/', index)
application.add_route('hello', '/hello', hello)
from wsgiref.simple_server import make_server
httpd = make_server('', 8000, application)
print "Serving HTTP on port 8000..."
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment