How to return the result of BackgroundTasks as websocket answer in FastApi?

Viewed 24

I have the next code:

from fastapi import FastAPI, WebSocket, BackgroundTasks
import uvicorn
import time

app = FastAPI()


def run_model():
    ...
    ## code of the model
    answer = [1, 2, 3]
    ...
    results = {"message": "the model has been excuted succesfully!!", "results": answer}
    return results


@app.post("/execute-model")
async def ping(background_tasks: BackgroundTasks):
    background_tasks.add_task(run_model)
    return {"message": "the model is executing"}


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        ## Here I wnat the results of run_model
        await websocket.send_text(1)

if __name__ == "__main__":
    uvicorn.run(app, host="localhost", port=8001)

I need to make a post fecth to /execute-model. This endpoint will excute a run_model function as a background task. I need return the answer to the front when run_model() finish and I thought in use websockets but I don't know how do it. Help please.

0 Answers
Related