Skip to content
Myr

update docs about contexts

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 82c2e03 · Browse files · 9 files+74 added−124 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+74 added−124 removed

  • other:+74 added−124 removed

9 files+74 added−124 removed

modified:docs/patterns/sqlite3.rst-4 removed
28 unmodified lines
29or create an application context itself. At that point the ``get_db``30function can be used to get the current database connection. Whenever the31context is destroyed the database connection will be terminated.3233Note: if you use Flask 0.9 or older you need to use34``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g`35object was bound to the request and not application context.3633Example::3435 @app.route('/')36 def index():
111 unmodified lines
modified:docs/api.rst+14 added-42 removed
309 unmodified lines
310311.. autoclass:: flask.ctx.RequestContext312 :members:313314.. data:: _request_ctx_stack314.. data:: flask.globals.request_ctx315316 The internal :class:`~werkzeug.local.LocalStack` that holds317 :class:`~flask.ctx.RequestContext` instances. Typically, the318 :data:`request` and :data:`session` proxies should be accessed319 instead of the stack. It may be useful to access the stack in320 extension code.316 The current :class:`~flask.ctx.RequestContext`. If a request context317 is not active, accessing attributes on this proxy will raise a318 ``RuntimeError``.319322 The following attributes are always present on each layer of the323 stack:320 This is an internal object that is essential to how Flask handles321 requests. Accessing this should not be needed in most cases. Most322 likely you want :data:`request` and :data:`session` instead.323325 `app`326 the active Flask application.327328 `url_adapter`329 the URL adapter that was used to match the request.330331 `request`332 the current request object.333334 `session`335 the active session object.336337 `g`338 an object with all the attributes of the :data:`flask.g` object.339340 `flashes`341 an internal cache for the flashed messages.342343 Example usage::344345 from flask import _request_ctx_stack346347 def get_session():348 ctx = _request_ctx_stack.top349 if ctx is not None:350 return ctx.session351324.. autoclass:: flask.ctx.AppContext325 :members:326355.. data:: _app_ctx_stack327.. data:: flask.globals.app_ctx328357 The internal :class:`~werkzeug.local.LocalStack` that holds358 :class:`~flask.ctx.AppContext` instances. Typically, the359 :data:`current_app` and :data:`g` proxies should be accessed instead360 of the stack. Extensions can access the contexts on the stack as a361 namespace to store data.329 The current :class:`~flask.ctx.AppContext`. If an app context is not330 active, accessing attributes on this proxy will raise a331 ``RuntimeError``.332363 .. versionadded:: 0.9333 This is an internal object that is essential to how Flask handles334 requests. Accessing this should not be needed in most cases. Most335 likely you want :data:`current_app` and :data:`g` instead.336337.. autoclass:: flask.blueprints.BlueprintSetupState338 :members:339
410 unmodified lines
modified:docs/appcontext.rst-8 removed
134 unmodified lines
135136Accessing ``db`` will call ``get_db`` internally, in the same way that137:data:`current_app` works.138139----139141If you're writing an extension, :data:`g` should be reserved for user142code. You may store internal data on the context itself, but be sure to143use a sufficiently unique name. The current context is accessed with144:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see145:doc:`/extensiondev`.146147140Events and Signals141------------------142143The application will call functions registered with
6 unmodified lines
modified:docs/extensiondev.rst-6 removed
185 unmodified lines
186when the application context ends. If it should only be valid during a187request, or would not be used in the CLI outside a reqeust, use188:meth:`~flask.Flask.teardown_request`.189190An older technique for storing context data was to store it on191``_app_ctx_stack.top`` or ``_request_ctx_stack.top``. However, this just192moves the same namespace collision problem elsewhere (although less193likely) and modifies objects that are very internal to Flask's194operations. Prefer storing data under a unique name in ``g``.190196191Views and Models192----------------193194Your extension views might want to interact with specific models in your
110 unmodified lines
modified:docs/reqcontext.rst+13 added-12 removed
35 unmodified lines
36context, which also pushes an :doc:`app context </appcontext>`. When the37request ends it pops the request context then the application context.3839The context is unique to each thread (or other worker type).40:data:`request` cannot be passed to another thread, the other thread41will have a different context stack and will not know about the request42the parent thread was pointing to.40:data:`request` cannot be passed to another thread, the other thread has41a different context space and will not know about the request the parent42thread was pointing to.4344Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`45for more information on how this works internally.44Context locals are implemented using Python's :mod:`contextvars` and45Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the46lifetime of context vars automatically, and local proxy wraps that47low-level interface to make the data easier to work with.484950Manually Push a Context51-----------------------
36 unmodified lines
88---------------------8990The :meth:`Flask.wsgi_app` method is called to handle each request. It91manages the contexts during the request. Internally, the request and90application contexts work as stacks, :data:`_request_ctx_stack` and91:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the92application contexts work like stacks. When contexts are pushed, the93proxies that depend on them are available and point at information from93the top context on the stack.94the top item.9596When the request starts, a :class:`~ctx.RequestContext` is created and97pushed, which creates and pushes an :class:`~ctx.AppContext` first if98a context for that application is not already the top context. While99these contexts are pushed, the :data:`current_app`, :data:`g`,100:data:`request`, and :data:`session` proxies are available to the101original thread handling the request.102102Because the contexts are stacks, other contexts may be pushed to change103the proxies during a request. While this is not a common pattern, it104can be used in advanced applications to, for example, do internal105redirects or chain different applications together.103Other contexts may be pushed to change the proxies during a request.104While this is not a common pattern, it can be used in advanced105applications to, for example, do internal redirects or chain different106applications together.107108After the request is dispatched and a response is generated and sent,109the request context is popped, which then pops the application context.110Immediately before they are popped, the :meth:`~Flask.teardown_request`
137 unmodified lines
modified:src/flask/app.py+19 added-18 removed
1282 unmodified lines
1283 return f12841285 @setupmethod1286 def teardown_appcontext(self, f: T_teardown) -> T_teardown:1287 """Registers a function to be called when the application context1288 ends. These functions are typically also called when the request1289 context is popped.1287 """Registers a function to be called when the application1288 context is popped. The application context is typically popped1289 after the request context for each request, at the end of CLI1290 commands, or after a manually pushed context ends.12911291 Example::1292 .. code-block:: python12931293 ctx = app.app_context()1294 ctx.push()1295 ...1296 ctx.pop()1294 with app.app_context():1295 ...12961298 When ``ctx.pop()`` is executed in the above example, the teardown1299 functions are called just before the app context moves from the1300 stack of active contexts. This becomes relevant if you are using1301 such constructs in tests.1297 When the ``with`` block exits (or ``ctx.pop()`` is called), the1298 teardown functions are called just before the app context is1299 made inactive. Since a request context typically also manages an1300 application context it would also be called when you pop a1301 request context.13021303 Since a request context typically also manages an application1304 context it would also be called when you pop a request context.1303 When a teardown function was called because of an unhandled1304 exception it will be passed an error object. If an1305 :meth:`errorhandler` is registered, it will handle the exception1306 and the teardown will not receive it.13071306 When a teardown function was called because of an unhandled exception1307 it will be passed an error object. If an :meth:`errorhandler` is1308 registered, it will handle the exception and the teardown will not1309 receive it.1308 Teardown functions must avoid raising exceptions. If they1309 execute code that might fail they must surround that code with a1310 ``try``/``except`` block and log any errors.13111312 The return values of teardown functions are ignored.13131314 .. versionadded:: 0.9
1010 unmodified lines
modified:src/flask/ctx.py+8 added-10 removed
225 unmodified lines
226 return _cv_req.get(None) is not None227228229class AppContext:230 """The application context binds an application object implicitly231 to the current thread or greenlet, similar to how the232 :class:`RequestContext` binds request information. The application233 context is also implicitly created if a request context is created234 but the application is not on top of the individual application235 context.230 """The app context contains application-specific information. An app231 context is created and pushed at the beginning of each request if232 one is not already active. An app context is also pushed when233 running CLI commands.234 """235236 def __init__(self, app: "Flask") -> None:237 self.app = app
37 unmodified lines
275 self.pop(exc_value)276277278class RequestContext:281 """The request context contains all request relevant information. It is282 created at the beginning of the request and pushed to the283 `_request_ctx_stack` and removed at the end of it. It will create the284 URL adapter and request object for the WSGI environment provided.279 """The request context contains per-request information. The Flask280 app creates and pushes it at the beginning of the request, then pops281 it at the end of the request. It will create the URL adapter and282 request object for the WSGI environment provided.283284 Do not attempt to use this class directly, instead use285 :meth:`~flask.Flask.test_request_context` and286 :meth:`~flask.Flask.request_context` to create this object.
151 unmodified lines
modified:src/flask/scaffold.py+16 added-19 removed
572 unmodified lines
573 return f574575 @setupmethod576 def teardown_request(self, f: T_teardown) -> T_teardown:577 """Register a function to be run at the end of each request,578 regardless of whether there was an exception or not. These functions579 are executed when the request context is popped, even if not an580 actual request was performed.577 """Register a function to be called when the request context is578 popped. Typically this happens at the end of each request, but579 contexts may be pushed manually as well during testing.580582 Example::581 .. code-block:: python582584 ctx = app.test_request_context()585 ctx.push()586 ...587 ctx.pop()583 with app.test_request_context():584 ...585589 When ``ctx.pop()`` is executed in the above example, the teardown590 functions are called just before the request context moves from the591 stack of active contexts. This becomes relevant if you are using592 such constructs in tests.586 When the ``with`` block exits (or ``ctx.pop()`` is called), the587 teardown functions are called just before the request context is588 made inactive.589594 Teardown functions must avoid raising exceptions. If595 they execute code that might fail they596 will have to surround the execution of that code with try/except597 statements and log any errors.590 When a teardown function was called because of an unhandled591 exception it will be passed an error object. If an592 :meth:`errorhandler` is registered, it will handle the exception593 and the teardown will not receive it.594599 When a teardown function was called because of an exception it will600 be passed an error object.595 Teardown functions must avoid raising exceptions. If they596 execute code that might fail they must surround that code with a597 ``try``/``except`` block and log any errors.598599 The return values of teardown functions are ignored.600 """601 self.teardown_request_funcs.setdefault(None, []).append(f)
288 unmodified lines
modified:src/flask/testing.py+4 added-5 removed
92 unmodified lines
93 return json_dumps(obj, **kwargs)949596class FlaskClient(Client):97 """Works like a regular Werkzeug test client but has some knowledge about98 how Flask works to defer the cleanup of the request context stack to the99 end of a ``with`` body when used in a ``with`` statement. For general100 information about how to use this class refer to101 :class:`werkzeug.test.Client`.97 """Works like a regular Werkzeug test client but has knowledge about98 Flask's contexts to defer the cleanup of the request context until99 the end of a ``with`` block. For general information about how to100 use this class refer to :class:`werkzeug.test.Client`.101102 .. versionchanged:: 0.12103 `app.test_client()` includes preset default environment, which can be104 set after instantiation of the `app.test_client()` object in
183 unmodified lines