Skip to content

Instantly share code, notes, and snippets.

@abegong
Last active July 25, 2018 00:44
Show Gist options
  • Save abegong/7608465 to your computer and use it in GitHub Desktop.
Save abegong/7608465 to your computer and use it in GitHub Desktop.
Example of regex-based tornado handler. (Doesn't actually work, but you get the idea.) NB: the database here is mongo, not SQL
class OpenTemplateHandler(tornado.web.RequestHandler):
def get_current_user(self):
return json.loads(self.get_secure_cookie("myapp-user"))
def get(self, path):
self.render(path+'.html')
class ApiHandler(BaseHandler):
@tornado.gen.coroutine
def get(self, path):
db = self.settings["db"]
if path == 'users':
users = yield motor.Op(db.users.find().to_list)
for u in users:
self.write(MyEncoder().encode(u))
elif path == 'objects':
objects = yield motor.Op(db.objects.find().to_list)
for a in objects:
self.write(MyEncoder().encode(a))
application = tornado.web.Application(
handlers = [
(r"/", RedirectHandler, {'url':'/home'}),
(r"/api/(.*?)/?", ApiHandler),
(r"/(.*?)/?", OpenTemplateHandler),
],
template_path=os.path.join(os.path.dirname(__file__), "html"),
static_path=os.path.join(os.path.dirname(__file__), "html"),
debug=True,
autoescape=None,
db=mongo_db,
cookie_secret=auth.cookie_secret,
login_url="/",
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment