On this page
Context Locals
You may find that you have some data during each request that you want to use across functions. Instead of passing these as arguments between every function, you may want to access them as global data. However, using global variables in Python web applications is not thread safe; different workers might interfere with each others’ data.
Instead of storing common data during a request using global variables, you must use context-local variables instead. A context local is defined/imported globally, but the data it contains is specific to the current thread, asyncio task, or greenlet. You won’t accidentally get or overwrite another worker’s data.
The current approach for storing per-context data in Python is the contextvars
module. Context vars store data per thread, async task, or greenlet. This replaces the older threading.local
which only handled threads.
Werkzeug provides wrappers around ContextVar
to make it easier to work with.
© 2007 Pallets
Licensed under the BSD 3-clause License.
https://werkzeug.palletsprojects.com/en/3.0.x/local/