-
Notifications
You must be signed in to change notification settings - Fork 25
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
Events are not received when dispatch() occurs in an asyncio.Task #34
Comments
Hi @smithk86, thank you for reporting the issue and for your patience. I've been thinking about this issue. When you said the actual work being done in an |
Do you know if there is any good way to tell when contextvars are being copied? Would you mind sharing it or pointing me to the resource? 🙏 thanks |
Below is a brief example of the route handler I was working on when I found this issue. The goal was to have the request start a long-running process but not have the client wait on the work being done. The results of the work would be published as an event. To answer your question, the context (with contextvars) are being copied when Cheers
|
thank you for the code sample. I can't think of a good general solution so far. |
@melvinkcx Setting My wrapper for
|
I banged my head against the wall with this one for a while before I found the problem.
Steps to reproduce:
asyncio.Task
which then dispatches a X process is complete afterwords.Task
are never receivedWhat is actually happening:
The issue is on dispatcher.py line 57. Starting in Python 3.7,
asyncio.Task
copies the current context fromcontextvars
into theTask
. When line 57 is reached, the code is told the event will be dispatched in the middleware as part of the request since the request was active at the time theTask
was created. In actuality, these events end up in the void as they should have been dispatched via_dispatch_as_task
.For now, anywhere an event needs to be dispatch within a
Task
, I importfastapi_events.in_req_res_cycle
into the code and runin_req_res_cycle.set(None)
. This forces_dispatch()
to process these events via_dispatch_as_task
.Edit: updated the link to include the specific commit revision
The text was updated successfully, but these errors were encountered: