Created
March 17, 2013 19:18
-
-
Save oxtopus/5183141 to your computer and use it in GitHub Desktop.
Quick hack to define web.py routes and handlers via decorators.
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 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() |
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 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