Skip to content
Discussion options

You must be logged in to vote

Context vars can be difficult to deal with, they can be complex and hard to debug, depending on how you use them. But given you already have some complex code, they are probably right for your use case.

Here are the caveats:

In FastAPI, you need to set them in an async dependency function or path operation, or an async middleware. If the function is non-async, FastAPI will run it on a thread worker. And if the context var is set on a thread worker, that is, let's say, a "child" context, so the value will not be propagated upwards.

So, you need to set the context in an async function.

Now, if the code that gets the data to be set is non-async blocking code (e.g. calling a DB), and if you r…

Replies: 5 comments 5 replies

This comment was marked as spam.

@claeyswo
Comment options

This comment was marked as spam.

@tiangolo
Comment options

This comment was marked as spam.

@YuriiMotov

This comment was marked as off-topic.

@christiansousadev

This comment was marked as off-topic.

@YuriiMotov

This comment was marked as off-topic.

This comment was marked as spam.

Comment options

You must be logged in to vote
0 replies
Answer selected by tiangolo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
6 participants