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
Provenance
- Commit
e0dad45- Tree
57e3f2f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
82c2e03
9 files changed+74 added−124 removed
modified:docs/patterns/sqlite3.rst-4 removed
28 unmodified lines29 or create an application context itself. At that point the ``get_db``30 function can be used to get the current database connection. Whenever the31 context is destroyed the database connection will be terminated.32 33-Note: 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`35-object was bound to the request and not application context.36-33 Example::34 35 @app.route('/')36 def index():111 unmodified linesmodified:docs/api.rst+14 added-42 removed
309 unmodified lines310 311 .. autoclass:: flask.ctx.RequestContext312 :members:313 314-.. data:: _request_ctx_stack314+.. data:: flask.globals.request_ctx315 316- 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``.319 322- 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.323 325- `app`326- the active Flask application.327-328- `url_adapter`329- the URL adapter that was used to match the request.330-331- `request`332- the current request object.333-334- `session`335- the active session object.336-337- `g`338- an object with all the attributes of the :data:`flask.g` object.339-340- `flashes`341- an internal cache for the flashed messages.342-343- Example usage::344-345- from flask import _request_ctx_stack346-347- def get_session():348- ctx = _request_ctx_stack.top349- if ctx is not None:350- return ctx.session351-324 .. autoclass:: flask.ctx.AppContext325 :members:326 355-.. data:: _app_ctx_stack327+.. data:: flask.globals.app_ctx328 357- 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``.332 363- .. 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.336 337 .. autoclass:: flask.blueprints.BlueprintSetupState338 :members:339 410 unmodified linesmodified:docs/appcontext.rst-8 removed
134 unmodified lines135 136 Accessing ``db`` will call ``get_db`` internally, in the same way that137 :data:`current_app` works.138 139-----139 141-If you're writing an extension, :data:`g` should be reserved for user142-code. You may store internal data on the context itself, but be sure to143-use a sufficiently unique name. The current context is accessed with144-:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see145-:doc:`/extensiondev`.146-147-140 Events and Signals141 ------------------142 143 The application will call functions registered with6 unmodified linesmodified:docs/extensiondev.rst-6 removed
185 unmodified lines186 when the application context ends. If it should only be valid during a187 request, or would not be used in the CLI outside a reqeust, use188 :meth:`~flask.Flask.teardown_request`.189 190-An older technique for storing context data was to store it on191-``_app_ctx_stack.top`` or ``_request_ctx_stack.top``. However, this just192-moves the same namespace collision problem elsewhere (although less193-likely) and modifies objects that are very internal to Flask's194-operations. Prefer storing data under a unique name in ``g``.190 196-191 Views and Models192 ----------------193 194 Your extension views might want to interact with specific models in your110 unmodified linesmodified:docs/reqcontext.rst+13 added-12 removed
35 unmodified lines36 context, which also pushes an :doc:`app context </appcontext>`. When the37 request ends it pops the request context then the application context.38 39 The context is unique to each thread (or other worker type).40-:data:`request` cannot be passed to another thread, the other thread41-will have a different context stack and will not know about the request42-the parent thread was pointing to.40+:data:`request` cannot be passed to another thread, the other thread has41+a different context space and will not know about the request the parent42+thread was pointing to.43 44-Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`45-for more information on how this works internally.44+Context locals are implemented using Python's :mod:`contextvars` and45+Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the46+lifetime of context vars automatically, and local proxy wraps that47+low-level interface to make the data easier to work with.48 49 50 Manually Push a Context51 -----------------------36 unmodified lines88 ---------------------89 90 The :meth:`Flask.wsgi_app` method is called to handle each request. It91 manages the contexts during the request. Internally, the request and90-application contexts work as stacks, :data:`_request_ctx_stack` and91-:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the92+application contexts work like stacks. When contexts are pushed, the93 proxies that depend on them are available and point at information from93-the top context on the stack.94+the top item.95 96 When the request starts, a :class:`~ctx.RequestContext` is created and97 pushed, which creates and pushes an :class:`~ctx.AppContext` first if98 a context for that application is not already the top context. While99 these contexts are pushed, the :data:`current_app`, :data:`g`,100 :data:`request`, and :data:`session` proxies are available to the101 original thread handling the request.102 102-Because the contexts are stacks, other contexts may be pushed to change103-the proxies during a request. While this is not a common pattern, it104-can be used in advanced applications to, for example, do internal105-redirects or chain different applications together.103+Other contexts may be pushed to change the proxies during a request.104+While this is not a common pattern, it can be used in advanced105+applications to, for example, do internal redirects or chain different106+applications together.107 108 After the request is dispatched and a response is generated and sent,109 the request context is popped, which then pops the application context.110 Immediately before they are popped, the :meth:`~Flask.teardown_request`137 unmodified linesmodified:src/flask/app.py+19 added-18 removed
1282 unmodified lines1283 return f1284 1285 @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.1291 1291- Example::1292+ .. code-block:: python1293 1293- ctx = app.app_context()1294- ctx.push()1295- ...1296- ctx.pop()1294+ with app.app_context():1295+ ...1296 1298- 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.1302 1303- 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.1307 1306- 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.1311 1312 The return values of teardown functions are ignored.1313 1314 .. versionadded:: 0.91010 unmodified linesmodified:src/flask/ctx.py+8 added-10 removed
225 unmodified lines226 return _cv_req.get(None) is not None227 228 229 class 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 """235 236 def __init__(self, app: "Flask") -> None:237 self.app = app37 unmodified lines275 self.pop(exc_value)276 277 278 class 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.283 284 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 linesmodified:src/flask/scaffold.py+16 added-19 removed
572 unmodified lines573 return f574 575 @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.580 582- Example::581+ .. code-block:: python582 584- ctx = app.test_request_context()585- ctx.push()586- ...587- ctx.pop()583+ with app.test_request_context():584+ ...585 589- 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.589 594- 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.594 599- 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.598 599 The return values of teardown functions are ignored.600 """601 self.teardown_request_funcs.setdefault(None, []).append(f)288 unmodified linesmodified:src/flask/testing.py+4 added-5 removed
92 unmodified lines93 return json_dumps(obj, **kwargs)94 95 96 class 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`.101 102 .. versionchanged:: 0.12103 `app.test_client()` includes preset default environment, which can be104 set after instantiation of the `app.test_client()` object in183 unmodified lines