It's seem like fastapi asynchronous background tasks blocks other requests? but it seems my problem is a bit different
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
db = Database()
async def task(data):
otherdata = await db.fetch("some sql")
await db.execute("insert otherdata sql",otherdata) # this blocks other api requests when excute'time too long.
@app.post("/profile")
async def profile(data: Data, background_tasks: BackgroundTasks):
background_tasks.add_task(task, data)
return {}
But when not define async it will not block other api request. (https://fastapi.tiangolo.com/tutorial/background-tasks/)
from fastapi import BackgroundTasks, FastAPI
from time import sleep
app = FastAPI()
db = Database()
def task(data):
for x in range(10):
sleep(1)
print(x)
@app.post("/profile")
async def profile(data: Data, background_tasks: BackgroundTasks):
background_tasks.add_task(task, data)
return {}
--> My prolem is When I excute sql (long execution time), i must be using async/await but using with background task of fast api, it will block other api request. So Is there any way I define my task is sync and excute sql by async/await.