!/usr/bin/env python"""RESTful web.py testingusage: python webapp.py 8080 [--test]>>> req = app.request('/mathematicians', method='POST')>>> req.status'400 Bad Request'>>> name = {'first': 'Beno\xc3\xaet', 'last': 'Mandelbrot'}>>> data = urllib.urlencode(name)>>> req = app.request('/mathematicians', method='POST', data=data)>>> req.status'201 Created'>>> created_path = req.headers['Location']>>> created_path'/mathematicians/b-mandelbrot'>>> fn = '{0} {1}
'.format(name['first'], name['last'])>>> assert fn in app.request(created_path).data"""import doctestimport urllibimport sysimport webpaths = ( '/mathematicians(/)?', 'Mathematicians', '/mathematicians/([a-z])-([a-z]{2,})', 'Mathematician')app = web.application(paths, globals())dbname = {True: 'test', False: 'production'}[sys.argv[-1] == '--test']db = {} # db = web.database(..., db='math_{0}'.format(dbname))class Mathematicians: def GET(self, slash=False): """list all mathematicians and form to create new one""" if slash: raise web.seeother('/mathematicians') mathematicians = db.items() # db.select(...) return web.template.Template("""$def with (mathematicians)Mathematicians Mathematicians
$if mathematicians:
- $for path, name in mathematicians:
- $name.first $name.last
Profile created for $name.first $name.last.
""")(path, name)class Mathematician: def GET(self, first_initial, last_name): """display mathematician""" key = '{0}-{1}'.format(first_initial, last_name) try: mathematician = db[key] # db.select(...) except KeyError: raise web.notfound() return web.template.Template("""$def with (name)$name.first $name.last
""")(mathematician)if __name__ == "__main__": if sys.argv[-1] == '--test': doctest.testmod() else: app.run()