Skip to content

Instantly share code, notes, and snippets.

@oxtopus
Created March 17, 2013 19:18
Show Gist options
  • Save oxtopus/5183141 to your computer and use it in GitHub Desktop.
Save oxtopus/5183141 to your computer and use it in GitHub Desktop.
Quick hack to define web.py routes and handlers via decorators.
import types
import web
urls = []
def GET(route):
def decorate(fn):
clsName = '%s_%s' % (fn.__name__, 'GET')
if clsName not in globals():
cls = type(clsName, (object,), {})
cls.GET = types.MethodType(fn, cls)
globals()[cls.__name__] = cls
urls.extend([route, clsName])
return fn
return decorate
@GET('/bar/(.*)')
def bar(cls, id):
return "Hello, %s" % id
@GET('/')
@GET('/foo')
def foo(cls, *args, **kwargs):
return "Hello, foo!"
app = web.application(urls, globals())
application = app.wsgifunc()
if __name__ == '__main__':
app.run()
import unittest2 as unittest
import webapp
class TestDecorator(unittest.TestCase):
def test_main(self):
result = webapp.app.request('/bar/Boo')
self.assertEqual(result.status, '200 OK')
self.assertEqual(result.data, 'Hello, Boo')
result = webapp.app.request('/')
self.assertEqual(result.status, '200 OK')
self.assertEqual(result.data, 'Hello, foo!')
result = webapp.app.request('/foo?bar=Bar')
self.assertEqual(result.status, '200 OK')
self.assertEqual(result.data, 'Hello, foo!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment