我有一个 API,它发布创建后台作业的作业,并且我想在另一个 GET api 上发送作业状态。如何实现这一目标?在background_work()
我将使用多重处理作为内部调用目标subprocess.call()
calls.
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
应用程序的,因为它在服务请求的同一个异步事件循环中运行,并且它会停止您的应用程序。而是将它们提交到线程池或进程池。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)