在FastAPI中获取后台任务的返回状态后台、状态、任务、FastAPI

2023-09-04 01:58:09 作者:逗比别闹快吃药

我有一个API,可以发布创建后台作业的作业,我想在另一个GET API上发送作业的状态。如何做到这一点呢?在background_work()函数中,我使用多处理,因为内部调用以subprocess.call()调用为目标。

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def background_work(data: str):
    # some computation on data and return it
    return status

@app.post("/post_job", status_code=HTTP_201_CREATED)
async def send_notification(data: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(background_work, data)
    return {"message": "Job Created, check status after some time!"}

@app.get("/get_status")
def status():
    #how to return status of job submitted to background task

推荐答案

目前无法使用FastAPI实现这一点,因为后台任务只是对发送响应后要调用的可调用函数的引用,它们不存储任何类型的状态。

后台配置任务如何通过设定配置项目的方式来管理和分配任务的详解

您必须使用芹菜或其他库。