]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Create UIModule proxies on demand instead of in RequestHandler init.
authorBen Darnell <ben@bendarnell.com>
Sun, 5 May 2013 16:58:34 +0000 (12:58 -0400)
committerBen Darnell <ben@bendarnell.com>
Sun, 5 May 2013 17:11:26 +0000 (13:11 -0400)
It would be nice to do something similar for UI methods, but it's tricker
and they are less common (there are three UIModules defined by default
for every handler).

tornado/web.py

index ff3572c8b9086e5fe0636a99c0ce593979b74354..f1f83b85aa01a42b3305aaca31bff00c2d963b3e 100644 (file)
@@ -104,6 +104,22 @@ except ImportError:
     from urllib.parse import urlencode  # py3
 
 
+class _UIModuleNamespace(object):
+    """Lazy namespace which creates UIModule proxies bound to a handler."""
+    def __init__(self, handler, ui_modules):
+        self.handler = handler
+        self.ui_modules = ui_modules
+
+    def __getitem__(self, key):
+        return self.handler._ui_module(key, self.ui_modules[key])
+
+    def __getattr__(self, key):
+        try:
+            return self[key]
+        except KeyError as e:
+            raise AttributeError(str(e))
+
+
 class RequestHandler(object):
     """Subclass this class and define `get()` or `post()` to make a handler.
 
@@ -136,9 +152,8 @@ class RequestHandler(object):
         # but could be clobbered by user additions to the namespace.
         # The template {% module %} directive looks in `_tt_modules` to avoid
         # possible conflicts.
-        self.ui["_tt_modules"] = ObjectDict(
-            (n, self._ui_module(n, m)) for n, m in
-            application.ui_modules.items())
+        self.ui["_tt_modules"] = _UIModuleNamespace(self,
+                                                    application.ui_modules)
         self.ui["modules"] = self.ui["_tt_modules"]
         self.clear()
         # Check since connection is not available in WSGI