Created
August 27, 2011 06:00
-
-
Save aodag/1175051 to your computer and use it in GitHub Desktop.
Greeting message wsgi application with various wsgi components
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 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