【发布时间】:2021-05-19 07:57:48
【问题描述】:
我想在 fastapi 中运行一个简单的后台任务,该任务在将其转储到数据库之前涉及一些计算。但是,计算会阻止它接收更多请求。
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
db = Database()
async def task(data):
otherdata = await db.fetch("some sql")
newdata = somelongcomputation(data,otherdata) # this blocks other requests
await db.execute("some sql",newdata)
@app.post("/profile")
async def profile(data: Data, background_tasks: BackgroundTasks):
background_tasks.add_task(task, data)
return {}
解决此问题的最佳方法是什么?
【问题讨论】:
-
如果计算量大且不涉及IO,最好使用多处理。
-
我正在使用 docker fastapi 进行部署,默认情况下它使用服务器的所有 cpu 核心。我不想使用像 celery 这样的其他服务,因为该产品仍处于原型设计阶段并且没有用户。