Closed frake23 closed 10 months ago
ContextVar is designed to be isolated for async tasks. Answer from ChatGPT:
ContextVar, introduced in Python 3.7 as part of the contextvars module, is designed to provide context-local storage. This means that each asynchronous task (like an async request in a web server) gets its own “view” of a ContextVar’s value. If two requests are processed at the same time and each sets a ContextVar to a different value (like “A” and “B”), each request will only see the value it set.
In your scenario:
- First request sets ContextVar to “A”: This value is local to the first request’s context.
- Second request sets ContextVar to “B”: This value is local to the second request’s context.
When these requests are processed in the event loop, each request will see the ContextVar value as it was set in their own context. So, the first request will see the value as “A”, and the second request will see it as “B”. The contexts are isolated, and the setting of the variable in one request does not affect the other.
Hello! Good example, thank you! I have a small question, would it work if two requests will be processed at the same time? First request sets ContextVar to value "A", second to value "B". Then these requests are processed in event loop while context is set to value "B", so session would be the same.
I might be not right, could you please tell me if i not? Thanks!