1

In my FastAPI route, I need to return a StreamingResponse to the user as each chunk of a text sentence gets generated.

However, the complete text sentence needs to be inserted into a database. Is there a way to do this?

@app.post("/foo_stream")
def foo_stream(input: Input, db: Session = Depends(get_db)):
    return StreamingResponse(
        generate_streaming_response(input),
        media_type="text/plain",
    )

    # Now that the streaming is done, how do you insert the entire text into our database?
gameveloster
  • 901
  • 1
  • 6
  • 18
  • 1
    You could have the `response` stored in a variable and use a `BackgroundTask` for saving it to the database - see [this answer](https://stackoverflow.com/a/76280152/17865804) and [this answer](https://stackoverflow.com/a/71221061/17865804). If you would like having a middleware for this task, please have a look at [this answer](https://stackoverflow.com/a/73464007/17865804) – Chris Jul 20 '23 at 04:28

0 Answers0