Debian Codegraph @

docs/discussion/contexts.rst

raw
1 .. _contexts:
2
3 Contexts
4 ========
5
6 Quart, like Flask, has two contexts the *application context* and the
7 *request context*. Both of these contexts exist per request and allow
8 the global proxies ``current_app``, ``request``, etc... to be resolved.
9 Note that these contexts are task local, and hence will not exist if a
10 task is spawned by ``ensure_future`` or ``create_task``.
11
12 The design principle of these contexts is that they are likely needed
13 in all routes, and hence rather than pass these objects around they
14 are made available via global proxies. This has its downsides, notably
15 all the arguments relating to global variables. Therefore, it is
16 recommended that these proxies are only used within routes so as to
17 isolate the scope.
18
19 Application Context
20 -------------------
21
22 The application context is a reference point for any information that
23 isn't specifically related to a request. This includes the app itself,
24 the ``g`` global object and a ``url_adapter`` bound only to the app. The
25 context is created and destroyed implicitly by the request context.
26
27 Request Context
28 ---------------
29
30 The request context is a reference point for any information that is
31 related to a request. This includes the request itself, a ``url_adapter``
32 bound to the request and the session. It is created and destroyed by
33 the :func:`~quart.Quart.handle_request` method per request.
34
35 Websocket Context
36 -----------------
37
38 The websocket context is analogous to the request context, but is
39 related only to websocket requests. It is created and destroyed by the
40 :func:`~quart.Quart.handle_websocket_request` method per websocket
41 connection.
42
43 Tasks and contexts
44 ------------------
45
46 Context is bound to a ContextVar and will be copied to tasks created
47 from an existing task. To explicitly copy a context Quart provides the
48 decorators :func:`~quart.ctx.copy_current_request_context` and
49 :func:`copy_current_websocket_context` which can be used as so,
50
51 .. code-block:: python
52
53 @app.route('/')
54 async def index():
55
56 @copy_current_request_context
57 async def background_task():
58 method = request.method
59 ...
60
61 asyncio.ensure_future(background_task())
62 ...
63
64 If you need to provide the ``request`` context in an asynchronous
65 generator, use the :func:`quart.helpers.stream_with_context` decorator
66 as discussed in :ref:`streaming_response`:
67
68 .. code-block:: python
69
70 @app.route('/')
71 async def index():
72
73 @stream_with_context
74 async def async_generator():
75 async for data in request.body:
76 yield data
77
78 await consume_data(async_generator())
79 ...
80
81 .. note:: These decorators must be used within an existing context, hence
82 the background task is defined as a nested function.