gpt4 book ai didi

python-3.x - 从 FastAPI 中的后台任务获取返回状态

转载 作者:行者123 更新时间:2023-12-03 13:50:23 26 4
gpt4 key购买 nike

我有一个 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,结合 concurrent.futures.ProcessPoolExecutor()和 asyncio 来管理长时间运行的作业。
如果您不想依赖其他模块( celery 等),您需要管理自己的工作状态,并将其存储在某个地方。我将它存储在数据库中,以便在重新启动服务器后可以恢复挂起的作业。
请注意,您不得在 background_tasks 中执行 CPU 密集型计算。应用程序,因为它运行在为请求提供服务的同一个异步事件循环中,它将停止您的应用程序。而是将它们提交到线程池或进程池。

关于python-3.x - 从 FastAPI 中的后台任务获取返回状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61836761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com