Request Disconnect / Cancelled Middleware #11360
hari01584
started this conversation in
Show and tell
Replies: 2 comments 2 replies
-
very good. maybe |
Beta Was this translation helpful? Give feedback.
0 replies
-
This middleware would stop background tasks as soon as it reached a coroutine. async def execute_background(instance):
print("Sleeping in the background:", instance)
await asyncio.sleep(2)
print("Finished", instance)
@app.get("/background")
async def background(background_tasks: fastapi.BackgroundTasks):
num_random = random.randint(1, 10000)
print("Running background, instance: ", num_random)
background_tasks.add_task(execute_background, num_random)
return {"random": num_random} This outputs the following
Happens because the request has finished (http.disconnect), which stops background tasks. Using |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This middleware handles request canceling in case of API routes used for autocompletion/etc, where very frequent/expensive requests are made.
How to test?
Simply open localhost:8000 and keep refreshing the page. You will see multiple requests spawn up! The heavy task in question is await asyncio.sleep(10) which will be completed in 10s, So you can keep waiting for 10s after few refreshes to see order of execution!
Outputs:
Before adding middleware:
After adding middleware:
Beta Was this translation helpful? Give feedback.
All reactions