In FastAPI, run_in_executor
and run_in_threadpool
both can let function running in other thread, and it seems to have the same behavior.
But what's difference between this ? And what's the best choice for using FastAPI?
Demo:
import asyncio
import time
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
app = FastAPI()
@app.get("/")
async def index():
result = await long_time_work()
result = await long_time_work2()
return {"message": result}
async def long_time_work():
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, time.sleep, 5)
return True
async def long_time_work2():
await run_in_threadpool(lambda: time.sleep(5))
return True