Skip to content

Instantly share code, notes, and snippets.

@patricklucas
Created February 28, 2012 04:56
Show Gist options
  • Save patricklucas/1929698 to your computer and use it in GitHub Desktop.
Save patricklucas/1929698 to your computer and use it in GitHub Desktop.
Mini framework
import re
import webob
import webob.exc
HTTP_METHODS = ('GET', 'POST', 'PUT')
class Apper(object):
routes = None
def __init__(self):
super(Apper, self).__init__()
self.routes = dict((method, []) for method in HTTP_METHODS)
def route(self, method, path):
def decorator(action):
self.routes[method].append((re.compile('^' + path + '$'), action))
return action
return decorator
def get(self, path):
return self.route('GET', path)
def post(self, path):
return self.route('POST', path)
def _route(self):
for path, action in self.routes[self.request.method]:
matches = path.match(self.request.path)
if matches:
return action(self, **matches.groupdict())
raise webob.exc.HTTPNotFound
def __call__(self, environ, start_response):
self.request = webob.Request(environ)
self.response = webob.Response(request=self.request)
try:
self.response.body = self._route()
except webob.exc.WSGIHTTPException as e:
return self.request.get_response(e)(environ, start_response)
else:
return self.response(environ, start_response)
import simplejson
from wsgiref.simple_server import make_server
from apper import Apper
app = Apper()
@app.get(r"/hello/(?P<name>[^\.]+)")
def hello(self, name=""):
return "Hello, %s!" % name
@app.get(r"/hello/(?P<name>[^\.]+)\.json")
def hello(self, name=""):
self.response.content_type = "application/json"
return simplejson.dumps({
'status': 'ok',
'response': "Hello, %s!" % name
})
make_server('localhost', 8000, app).serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment