Created
September 26, 2011 06:10
-
-
Save dmitric/1241698 to your computer and use it in GitHub Desktop.
DLC's tornado.web.RequestHandler add on's
This file contains hidden or 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
class BaseHandler(tornado.web.RequestHandler): | |
#lazy initializer of Connection reference | |
@property | |
def db(self): | |
if not hasattr(self, '_db'): | |
self._db = Connection(options.db_master, options.db_port)[options.db_name] | |
return self._db | |
#overriding the default get_current_user to use an encrypted, pickled python object | |
def get_current_user(self): | |
cookie_string = self.get_secure_cookie(options.cookie_user) | |
try: | |
return pickle.loads(cookie_string) | |
except: | |
return None | |
#this allows you to access alerts in a unified manner | |
#without relying on server side sessions | |
def get_flash_alerts(self): | |
alerts = self.get_secure_cookie(options.cookie_alerts) | |
try: | |
alerts = pickle.loads(alerts) | |
self.clear_cookie(options.cookie_alerts) | |
return alerts | |
except: | |
return None | |
#override the default render method to inject in the flash alerts, | |
#or other properties | |
def render(self, *args, **kwargs): | |
flash_alerts = self.get_flash_alerts() | |
if 'alerts' not in kwargs: | |
kwargs['alerts'] = flash_alerts | |
elif flash_alerts is not None: | |
kwargs['alerts'].extend(flash_alerts) | |
tornado.web.RequestHandler.render(self, *args, **kwargs) | |
#override the default error pages with your own html | |
def write_error(self, status_code, **kwargs): | |
error_trace = None | |
if self.settings.get("debug") and "exc_info" in kwargs: | |
import traceback | |
error_trace= "" | |
for line in traceback.format_exception(*kwargs["exc_info"]): | |
error_trace += line | |
self.render("base_error.html", status_code=status_code, error_trace=error_trace) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment