【发布时间】:2021-12-31 17:48:44
【问题描述】:
我目前正在开发一个具有多个端点的 API。其中之一是在数据库中注册数据,其他端点与简单的 CRUD 端点相关(通过 id 获取数据、获取所有数据、删除数据等)。
当注册数据端点被调用时,几乎立即将响应返回给 API,然后启动后台任务,我们在其中获取数据,必要时解压缩,等等。
我们为此使用 FastAPI 和异步函数。不过,我注意到的是,API 被后台任务的执行阻塞了。当我一次性将一个大文件上传到 S3 时(不是分块,我使用异步函数),这尤其糟糕,我必须等待完整文件的上传结束,然后另一个请求才能得到响应(例如在请求 get all data 端点时))。
我是并行和并发方面的专家,但我期待后台任务而不是阻止 API。
关于如何以不会阻止对 API 的新请求的方式运行这个长时间运行的后台任务的任何想法?芹菜最适合这个吗?
模拟示例:
@app.post("register endpoint")
async def register_data(datainput, backgroundtasks: BackgroundTasks):
#Do something
backgroundtasks.add_task(background_operation)
return JSONResponse(
status_code=200, content="Doing stuff")
)
async def background_operation():
#Doing stuff here
await function_that_uploads_data_to_s3
【问题讨论】:
-
你确定 uvicorn 是用 --workers
设置的吗? -
这里可以使用多线程...
标签: python asynchronous parallel-processing fastapi