flask.g is now on the app context and not the request context
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 61d43c7 · Browse files · 9 files·+71 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+71 added−20 removed
- other:+71 added−20 removed
Provenance
- Commit
1949c4a- Tree
5681ae2- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
61d43c7
9 files changed+71 added−20 removed
modified:docs/api.rst+4 added
256 unmodified lines257 258 Just store on this whatever you want. For example a database259 connection or the user that is currently logged in.260 261+ Starting with Flask 0.10 this is stored on the application context and262+ no longer on the request context which means it becomes available if263+ only the application context is bound and not yet a request.264+265 This is a proxy. See :ref:`notes-on-proxies` for more information.266 267 268 Useful Functions and Classes430 unmodified linesmodified:docs/upgrading.rst+7 added
34 unmodified lines35 36 In order to not break people's sessions it is possible to continue using37 the old session system by using the `Flask-OldSessions_` extension.38 39+Flask also started storing the :data:`flask.g` object on the application40+context instead of the request context. This change should be transparent41+for you but it means that you now can store things on the ``g`` object42+when there is no request context yet but an application context. The old43+``flask.Flask.request_globals_class`` attribute was renamed to44+:attr:`flask.Flask.app_ctx_globals_class`.45+46 .. _Flask-OldSessions: http://packages.python.org/Flask-OldSessions/47 48 Version 0.949 -----------323 unmodified linesmodified:flask/testsuite/appctx.py+3 added-3 removed
63 unmodified lines64 pass65 66 self.assert_equal(cleanup_stuff, [None])67 68- def test_custom_request_globals_class(self):68+ def test_custom_app_ctx_globals_class(self):69 class CustomRequestGlobals(object):70 def __init__(self):71 self.spam = 'eggs'72 app = flask.Flask(__name__)73- app.request_globals_class = CustomRequestGlobals74- with app.test_request_context():73+ app.app_ctx_globals_class = CustomRequestGlobals74+ with app.app_context():75 self.assert_equal(76 flask.render_template_string('{{ g.spam }}'), 'eggs')77 78 def test_context_refcounts(self):24 unmodified linesmodified:flask/testsuite/basic.py+4 added-1 removed
1102 unmodified lines1103 with self.assert_raises(ZeroDivisionError):1104 c.get('/fail')1105 1106 self.assert_(flask._request_ctx_stack.top is not None)1107+ self.assert_(flask._app_ctx_stack.top is not None)1108+ # implicit appctx disappears too1107- flask._request_ctx_stack.pop()1109+ flask._request_ctx_stack.top.pop()1110 self.assert_(flask._request_ctx_stack.top is None)1111+ self.assert_(flask._app_ctx_stack.top is None)1112 1113 1114 class ContextTestCase(FlaskTestCase):1115 125 unmodified linesmodified:flask/app.py+19 added-3 removed
26 unmodified lines27 locked_cached_property, _endpoint_from_view_func, find_package28 from . import json29 from .wrappers import Request, Response30 from .config import ConfigAttribute, Config31-from .ctx import RequestContext, AppContext, _RequestGlobals31+from .ctx import RequestContext, AppContext, _AppCtxGlobals32 from .globals import _request_ctx_stack, request33 from .sessions import SecureCookieSessionInterface34 from .module import blueprint_is_module35 from .templating import DispatchingJinjaLoader, Environment, \120 unmodified lines156 #: 2. Add a property for lazy per-request database connectors.157 #: 3. Return None instead of AttributeError on expected attributes.158 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.159 #:160+ #: In Flask 0.9 this property was called `request_globals_class` but it161+ #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the162+ #: flask.g object is not application context scoped.163+ #:160- #: .. versionadded:: 0.9161- request_globals_class = _RequestGlobals164+ #: .. versionadded:: 0.10165+ app_ctx_globals_class = _AppCtxGlobals166 167+ # Backwards compatibility support168+ def _get_request_globals_class(self):169+ return self.app_ctx_globals_class170+ def _set_request_globals_class(self, value):171+ from warnings import warn172+ warn(DeprecationWarning('request_globals_class attribute is now '173+ 'called app_ctx_globals_class'))174+ self.app_ctx_globals_class = value175+ request_globals_class = property(_get_request_globals_class,176+ _set_request_globals_class)177+ del _get_request_globals_class, _set_request_globals_class178+179 #: The debug flag. Set this to `True` to enable debugging of the180 #: application. In debug mode the debugger will kick in when an unhandled181 #: exception ocurrs and the integrated server will automatically reload182 #: the application if changes in the code are detected.1592 unmodified linesmodified:flask/ctx.py+9 added-2 removed
15 unmodified lines16 from .globals import _request_ctx_stack, _app_ctx_stack17 from .module import blueprint_is_module18 19 20-class _RequestGlobals(object):20+class _AppCtxGlobals(object):21 """A plain object."""22 pass23 24 75 unmodified lines100 101 def __init__(self, app):102 self.app = app103 self.url_adapter = app.create_url_adapter(None)104+ self.g = app.app_ctx_globals_class()105 106 # Like request context, app contexts can be pushed multiple times107 # but there a basic "refcount" is enough to track them.108 self._refcnt = 055 unmodified lines164 def __init__(self, app, environ):165 self.app = app166 self.request = app.request_class(environ)167 self.url_adapter = app.create_url_adapter(self.request)167- self.g = app.request_globals_class()168 self.flashes = None169 self.session = None170 171 # Request contexts can be pushed multiple times and interleaved with22 unmodified lines194 bp = app.blueprints.get(blueprint)195 if bp is not None and blueprint_is_module(bp):196 self.request._is_old_module = True197 198+ def _get_g(self):199+ return _app_ctx_stack.top.g200+ def _set_g(self, value):201+ _app_ctx_stack.top.g = value202+ g = property(_get_g, _set_g)203+ del _get_g, _set_g204+205 def match_request(self):206 """Can be overridden by a subclass to hook into the matching207 of the request.208 """95 unmodified linesmodified:flask/globals.py+12 added-4 removed
11 unmodified lines12 13 from functools import partial14 from werkzeug.local import LocalStack, LocalProxy15 16+16-def _lookup_object(name):17+def _lookup_req_object(name):18 top = _request_ctx_stack.top19 if top is None:20 raise RuntimeError('working outside of request context')21 return getattr(top, name)22 23 24+def _lookup_app_object(name):25+ top = _app_ctx_stack.top26+ if top is None:27+ raise RuntimeError('working outside of application context')28+ return getattr(top, name)29+30+31 def _find_app():32 top = _app_ctx_stack.top33 if top is None:34 raise RuntimeError('working outside of application context')3 unmodified lines38 # context locals39 _request_ctx_stack = LocalStack()40 _app_ctx_stack = LocalStack()41 current_app = LocalProxy(_find_app)34-request = LocalProxy(partial(_lookup_object, 'request'))35-session = LocalProxy(partial(_lookup_object, 'session'))36-g = LocalProxy(partial(_lookup_object, 'g'))42+request = LocalProxy(partial(_lookup_req_object, 'request'))43+session = LocalProxy(partial(_lookup_req_object, 'session'))44+g = LocalProxy(partial(_lookup_app_object, 'g'))modified:flask/templating.py+8 added-7 removed
20 unmodified lines21 """Default template context processor. Injects `request`,22 `session` and `g`.23 """24 reqctx = _request_ctx_stack.top25- if reqctx is None:26- return {}27- return dict(28- request=reqctx.request,29- session=reqctx.session,30- g=reqctx.g31- )25+ appctx = _app_ctx_stack.top26+ rv = {}27+ if appctx is not None:28+ rv['g'] = appctx.g29+ if reqctx is not None:30+ rv['request'] = reqctx.request31+ rv['session'] = reqctx.session32+ return rv33 34 35 class Environment(BaseEnvironment):36 """Works like a regular Jinja2 environment but has some additional106 unmodified linesmodified:CHANGES+5 added
32 unmodified lines33 - Added an option to generate non-ascii encoded JSON which should result34 in less bytes being transmitted over the network. It's disabled by35 default to not cause confusion with existing libraries that might expect36 ``flask.json.dumps`` to return bytestrings by default.37+- ``flask.g`` is now stored on the app context instead of the request38+ context.39+- ``flask.Flask.request_globals_class`` got renamed to40+ ``flask.Flask.app_ctx_globals_class`` which is a better name to what it41+ does since 0.10.42 43 Version 0.944 -----------45 365 unmodified lines