我想在 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 {}
Run Code Online (Sandbox Code Playgroud)
解决此问题的最佳方法是什么?