Last active
December 12, 2015 09:48
-
-
Save callum/4753951 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
import tornado.ioloop | |
import tornado.web | |
import functools | |
class template_method(object): | |
_methods = [] | |
def __init__(self, _method): | |
self._methods.append(_method) | |
@staticmethod | |
def _get_method(handler, method): | |
if isinstance(method, property): | |
method = method.fget | |
value = method(handler) | |
else: | |
value = functools.partial(method, handler) | |
return (method.__name__, value) | |
@classmethod | |
def get_methods(cls, handler): | |
return dict(cls._get_method(handler, m) for m in cls._methods) | |
class BaseHandler(tornado.web.RequestHandler): | |
# Override render_string, passing in additional methods | |
def render_string(self, *args, **kwargs): | |
template_kwargs = template_method.get_methods(self) | |
template_kwargs.update(kwargs) | |
return tornado.web.RequestHandler.render_string( | |
self, *args, **template_kwargs) | |
# Define methods available to handlers that subclass BaseHandler | |
@template_method | |
def reverse(self, text): | |
return text[::-1] | |
# Can be used in conjuction with a @property decorator | |
@template_method | |
@property | |
def site_name(self): | |
return "My site name" | |
"""template.html: | |
{{ reverse("My string") }} | |
""" | |
class MainHandler(BaseHandler): | |
def get(self): | |
# Output: gnirts yM | |
self.render("template.html") | |
class OtherHandler(BaseHandler): | |
def get(self): | |
# Predefined methods can be overridden | |
# Output: My string | |
self.render("template.html", reverse=lambda s: s) | |
if __name__ == "__main__": | |
application = tornado.web.Application([ | |
(r"/", MainHandler), | |
(r"/other", OtherHandler) | |
]) | |
application.listen(8888) | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment