[feature request] support ContextVars
See original GitHub issueIt seem that setting context variables in on_startup
is not supported.
My naïve understanding is that there needs to be a new (copied) context in which all of on_startup
, asgi request and then on_shutdown
are ran.
Otherwise, the value that’s been set is not accessible in the request handlers and/or the context var cannot be reset in the shutdown function using the token that was generated in the startup function.
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (4 by maintainers)
Top Results From Across the Web
add support for async contextvars #153 - GitHub
add support for async contextvars #153 ... I opened https://bugs.python.org/issue40320 to officially request the ability to pass context to task ...
Read more >contextvars — Context Variables — Python 3.11.1 ...
This module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables....
Read more >Understanding Python contextvars - Stack Overflow
Context variables are natively supported in asyncio and are ready to be used without any extra configuration. Because when a Task is created...
Read more >Upgrade Guide — django-structlog 4.0.1 documentation
django-structlog drops support of django below 3.2. ... 'email', '')) structlog.contextvars.bind_contextvars(user_email=getattr(request.user, 'email', '')) ...
Read more >Context Variables in Python - GeeksforGeeks
The ContextVar class present in contextvars module, which is used to declare and work with context variables in python. Note: This is supported...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@florimondmanca I think you may be right, I’m using fastapi/starlette/uvicorn and andeed my context var setup needs tricky context saving/switching because lifespan is a separate call (from middleware’s point of view).
A few questions to get the investigation going…
If we know in what happens in these situations then we may be able to pinpoint where the problem might be.
Now that I think about it, I said at the beginning of this thread that lifespan is a long running task, but more precisely I believe that’s how Uvicorn does it. Still, this « token was created in a different Context » error seems different, even odd. I looked up Starlette code, and the lifespan_context there runs as a single async with call, no strange task stuff going on. Which strengthens my belief that we might want to look at how Uvicorn runs lifespan…