Skip to content
Myr

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

9 files+71 added−20 removed

modified:docs/api.rst+4 added
256 unmodified lines
257258 Just store on this whatever you want. For example a database259 connection or the user that is currently logged in.260261 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.264265 This is a proxy. See :ref:`notes-on-proxies` for more information.266267268Useful Functions and Classes
430 unmodified lines
modified:docs/upgrading.rst+7 added
34 unmodified lines
3536In order to not break people's sessions it is possible to continue using37the old session system by using the `Flask-OldSessions_` extension.3839Flask also started storing the :data:`flask.g` object on the application40context instead of the request context. This change should be transparent41for you but it means that you now can store things on the ``g`` object42when 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`.4546.. _Flask-OldSessions: http://packages.python.org/Flask-OldSessions/4748Version 0.949-----------
323 unmodified lines
modified:flask/testsuite/appctx.py+3 added-3 removed
63 unmodified lines
64 pass6566 self.assert_equal(cleanup_stuff, [None])6768 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')7778 def test_context_refcounts(self):
24 unmodified lines
modified:flask/testsuite/basic.py+4 added-1 removed
1102 unmodified lines
1103 with self.assert_raises(ZeroDivisionError):1104 c.get('/fail')11051106 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)111211131114class ContextTestCase(FlaskTestCase):1115
125 unmodified lines
modified:flask/app.py+19 added-3 removed
26 unmodified lines
27 locked_cached_property, _endpoint_from_view_func, find_package28from . import json29from .wrappers import Request, Response30from .config import ConfigAttribute, Config31from .ctx import RequestContext, AppContext, _RequestGlobals31from .ctx import RequestContext, AppContext, _AppCtxGlobals32from .globals import _request_ctx_stack, request33from .sessions import SecureCookieSessionInterface34from .module import blueprint_is_module35from .templating import DispatchingJinjaLoader, Environment, \
120 unmodified lines
156 #: 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 = _AppCtxGlobals166167 # 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_class178179 #: 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 lines
modified:flask/ctx.py+9 added-2 removed
15 unmodified lines
16from .globals import _request_ctx_stack, _app_ctx_stack17from .module import blueprint_is_module181920class _RequestGlobals(object):20class _AppCtxGlobals(object):21 """A plain object."""22 pass2324
75 unmodified lines
100101 def __init__(self, app):102 self.app = app103 self.url_adapter = app.create_url_adapter(None)104 self.g = app.app_ctx_globals_class()105106 # Like request context, app contexts can be pushed multiple times107 # but there a basic "refcount" is enough to track them.108 self._refcnt = 0
55 unmodified lines
164 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 = None170171 # Request contexts can be pushed multiple times and interleaved with
22 unmodified lines
194 bp = app.blueprints.get(blueprint)195 if bp is not None and blueprint_is_module(bp):196 self.request._is_old_module = True197198 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_g204205 def match_request(self):206 """Can be overridden by a subclass to hook into the matching207 of the request.208 """
95 unmodified lines
modified:flask/globals.py+12 added-4 removed
11 unmodified lines
1213from functools import partial14from werkzeug.local import LocalStack, LocalProxy151616def _lookup_object(name):17def _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)222324def _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)293031def _find_app():32 top = _app_ctx_stack.top33 if top is None:34 raise RuntimeError('working outside of application context')
3 unmodified lines
38# context locals39_request_ctx_stack = LocalStack()40_app_ctx_stack = LocalStack()41current_app = LocalProxy(_find_app)34request = LocalProxy(partial(_lookup_object, 'request'))35session = LocalProxy(partial(_lookup_object, 'session'))36g = LocalProxy(partial(_lookup_object, 'g'))42request = LocalProxy(partial(_lookup_req_object, 'request'))43session = LocalProxy(partial(_lookup_req_object, 'session'))44g = LocalProxy(partial(_lookup_app_object, 'g'))
modified:flask/templating.py+8 added-7 removed
20 unmodified lines
21 """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 rv333435class Environment(BaseEnvironment):36 """Works like a regular Jinja2 environment but has some additional
106 unmodified lines
modified:CHANGES+5 added
32 unmodified lines
33- 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.4243Version 0.944-----------45
365 unmodified lines