FastAPI 中的後台作業:非同步運作函數
在FastAPI 中,當您想要執行不應阻塞的非同步操作時,後台函數是必需的或延遲主要API 操作。讓我們探討一下如何有效地設定後台作業。
1.基於執行緒的後台任務:
啟動執行緒是在後台運行函數的簡單方法:
def start_worker(): print('[main]: starting worker...') my_worker = worker.Worker() my_worker.working_loop() # this function prints "hello" every 5 seconds if __name__ == '__main__': print('[main]: starting...') uvicorn.run(app, host="0.0.0.0", port=8000, reload=True) _worker_thread = Thread(target=start_worker, daemon=False) _worker_thread.start()
但是,這種方法有一個限制:它會阻塞主執行緒的執行。為了避免這種情況,請在主API 進程之前啟動線程,如下所示:
_worker_thread.start() uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)
2.基於事件的後台任務:
另一種選擇是使用基於事件的調度程序:
import sched, time from threading import Thread from fastapi import FastAPI import uvicorn app = FastAPI() s = sched.scheduler(time.time, time.sleep) def print_event(sc): print("Hello") sc.enter(5, 1, print_event, (sc,)) def start_scheduler(): s.enter(5, 1, print_event, (s,)) s.run() @app.on_event("startup") async def startup_event(): thread = Thread(target=start_scheduler) thread.start() if __name__ == '__main__': uvicorn.run(app, host="0.0.0.0", port=8000)
3。 AsyncIO 後台任務:
如果您的後台函數是異步的,您可以使用 asyncio.create_task() 函數:
from fastapi import FastAPI from contextlib import asynccontextmanager import asyncio async def print_task(s): while True: print('Hello') await asyncio.sleep(s) @asynccontextmanager async def lifespan(app: FastAPI): # Run at startup asyncio.create_task(print_task(5)) yield # Run on shutdown (if required) print('Shutting down...') app = FastAPI(lifespan=lifespan)
以上是如何在FastAPI中高效運行後台作業?的詳細內容。更多資訊請關注PHP中文網其他相關文章!