-
-
Notifications
You must be signed in to change notification settings - Fork 382
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unexpected ContextVar
handling for lifespan context managers
#3781
Comments
ContextVar
handling with AsyncTestClient
ContextVar
handling for lifespan context managers
vey interesting, I played a litttle with it, changing lifespan to the old way with on_startup / on_sutdown and the result is even weirder. I didn't go through all this thread but that seems related pytest-dev/pytest-asyncio#127 note on my "tests" I didnt use pytest-asyncio but anyio |
It looks like this is expected behavior in Starlette/FastAPI. The response there is pretty turse so it's hard to see exactly why. |
If this turns out to be a fundamental limitation it might be nice to support dependencies that have side effects but don't actually return a value. I could imagine something similar to Pytest's auto use fixtures: VAR = ContextVar("VAR", default=0)
async def set_var() -> AsyncIterator[None]:
token = VAR.set(1)
try:
yield
finally:
VAR.reset(token)
@get("/", dependencies={"set_var": Provide(set_var, always=True)})
async def get_thing() -> None:
assert VAR.get() == 1 |
yep, pytest-asyncio might add another layer of complexity but this fails without regardless so the issue lies elsewhere, now adding some goold old-style prints to this:
I get this log, note that there is something going on if I understand it clearly with the way the var is created / initialized as the handler seems to not use the same var that was created in lifespan
|
Here's a longer running issue: encode/uvicorn#1151 |
For additional context (😉) here's related Pytest issue. |
Description
A
ContextVar
set within alifespan
context manager is not available inside request handlers. By contrast, doing the same thing via an application level dependency does appear set in the require handler.MCVE
Steps to reproduce
Run the example above. Either via
python example.py
oruvicorn example:app
and check the/example
route.We should expect the response to be
1
since that's what's set during thelifespan
context manager, but it's always 0.If you instead swap the
lifespan
context manager for a dependency it works as expected:Litestar Version
2.12.1
Platform
Note
While we are open for sponsoring on GitHub Sponsors and
OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.
Check out all issues funded or available for funding on our Polar.sh dashboard
The text was updated successfully, but these errors were encountered: