+ @contextmanager
+ def gen_context(self, ctx=None, **kwargs):
+ """
+ Attach contextual information to request, or generate a context object
+
+ This avoids global variables; various utilities and contextual
+ information (current translation, etc) are attached to this
+ object.
+ """
+ if DISABLE_GLOBALS:
+ with self.db_manager.session_scope() as db:
+ yield self._gen_context(db, ctx)
+ else:
+ yield self._gen_context(self.db, ctx)
+
+ def _gen_context(self, db, ctx, **kwargs):
+ # Set up context
+ # --------------
+
+ # Is a context provided?
+ if ctx is None:
+ ctx = Context()
+
+ # Attach utilities
+ # ----------------
+
+ # Attach self as request.app
+ # Also attach a few utilities from request.app for convenience?
+ ctx.app = self
+
+ ctx.db = db
+
+ ctx.staticdirect = self.staticdirector
+
+ # Do special things if this is a request
+ # --------------------------------------
+ if isinstance(ctx, Request):
+ ctx = self._request_only_gen_context(ctx)
+
+ return ctx
+
+ def _request_only_gen_context(self, request):
+ """
+ Requests get some extra stuff attached to them that's not relevant
+ otherwise.
+ """
+ # Do we really want to load this via middleware? Maybe?
+ request.session = self.session_manager.load_session_from_cookie(request)
+
+ request.locale = translate.get_locale_from_request(request)
+
+ # This should be moved over for certain, but how to deal with
+ # request.locale?
+ request.template_env = template.get_jinja_env(
+ self, self.template_loader, request.locale)
+
+ mg_request.setup_user_in_request(request)
+
+ ## Routing / controller loading stuff
+ request.map_adapter = self.url_map.bind_to_environ(request.environ)
+
+ def build_proxy(endpoint, **kw):
+ try:
+ qualified = kw.pop('qualified')
+ except KeyError:
+ qualified = False
+
+ return request.map_adapter.build(
+ endpoint,
+ values=dict(**kw),
+ force_external=qualified)
+
+ request.urlgen = build_proxy
+
+ return request
+