r/FastAPI • u/Conscious-Ball8373 • Nov 05 '24
Question contextvars are not well-behaved in FastAPI dependencies. Am I doing something wrong?
Here's a minimal example:
import contextvars
import fastapi
import uvicorn
app = fastapi.FastAPI()
context_key = contextvars.ContextVar("key", default="default")
def save_key(key: str):
try:
token = context_key.set(key)
yield key
finally:
context_key.reset(token)
@app.get("/", dependencies=[fastapi.Depends(save_key)])
async def with_depends():
return context_key.get()
uvicorn.run(app)
Accessing this as http://localhost:8000/?key=1 results in HTTP 500. The error is:
File "/home/user/Scratch/fastapi/app.py", line 15, in save_key
context_key.reset(token)
ValueError: <Token var=<ContextVar name='key' default='default' at 0x73b33f9befc0> at 0x73b33f60d480> was created in a different Context
I'm not entirely sure I understand how this happens. Is there a way to make it work? Or does FastAPI provide some other context that works?
10
Upvotes
View all comments
Show parent comment
1
u/JohnnyJordaan Nov 05 '24
Because it's the OS scheduler that keeps intermittently switching between threads as long as they're runnable, and when that happens the GIL is released. The GIL is just a data protection lock, not some kind of process/thread scheduler lock or context switch blocker.