🤔 What is correct way to do DB operation after successfully streaming response? #11433
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def fake_video_streamer():
chunks = []
for i in range(10):
chunks.append(i)
yield b"some fake video bytes"
print("Streaming Done!", chunks)
# 🤔 How can I perform DB operation here?
@app.get("/")
async def main():
return StreamingResponse(fake_video_streamer())DescriptionHi 👋🏻 I'm streaming the LLM response and once it's completed I want to store the generated chunk ( I can pass DB dependency in Hence, What is the best way to do post-streaming insertion in DB? Thanks 😇 Operating SystemLinux Operating System DetailsN/A FastAPI Version0.110.1 Pydantic Version2.6.4 Python VersionPython 3.12.2 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
It seems that you should use the same approach as for background tasks (https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#background-tasks-and-dependencies-with-yield-technical-details)
So, you need to pass session_maker to your generator function (use dependency to get it in your endpoint function) and create session inside your generator function when you need to interact with DB. But I think this topic is a bit badly described in the documentation and should be improved. Also, it seems that this statement from the documentation is a bit confusing:
It's true for usual responses, but it's false for StreamingResponse: |
Beta Was this translation helpful? Give feedback.
Thanks to Doctor from discord I was able to finalize this:
We're still …