-
-
Notifications
You must be signed in to change notification settings - Fork 28
Description
Hi,
Thanks you for making this library available!
Reading the documentation here https://starlette-context.readthedocs.io/en/latest/fastapi.html#using-with-background-tasks explains how in FastAPI background tasks, the context set by the ContextMiddleware
is not available. Its should rather be passed in from the route that was called.
I think to see however, this context is available to the background task - intentionally or reliably so, that I don't know.
Here's a minimal example that illustrates what I see:
import asyncio
import collections
import random
import fastapi
import starlette_context.middleware
import uvicorn
from starlette_context import context
from starlette_context.plugins import RequestIdPlugin
app = fastapi.FastAPI(title="MRE")
app.add_middleware(
starlette_context.middleware.ContextMiddleware,
plugins=(RequestIdPlugin(validate=False),),
)
counter = collections.Counter()
async def backgrounded_task(nr):
print("MEH before sleep", nr, context)
await asyncio.sleep(random.randint(3, 7))
print("MEH after sleep", nr, context)
@app.get("/mre", name="MRE endpoint")
async def mre_endpoint(background_tasks: fastapi.BackgroundTasks):
counter["mre"] += 1
print("BLERK before backgrounded task", counter["mre"], context)
background_tasks.add_task(backgrounded_task, counter["mre"])
print("BLERK after backgrounded task", counter["mre"], context)
return {
"message": "MRE endpoint hit",
"context": str(context),
"counter": counter["mre"],
}
def serve():
config = uvicorn.Config(app, port=62666, server_header=False)
server = uvicorn.Server(config)
server.run()
if __name__ == "__main__":
serve()
When starting this app and requesting http://127.0.0.1:62666/mre
a few times in quick succession, you see, after some time "sleeping" the background tasks executed at random intervals. And each background task seems to have the correct context available to it, as set during the request cycle.
Since the docs are so adamant about the context vars being cleared after the response is sent, I wonder if a) I misunderstand the docs or b) what I see is a a result of a mistaken application of the middleware. Or c) perhaps something else?
I would appreciate any feedback on this issue.
Kind regards,
Jan-Wijbrand