在 FastAPI 端點使用 Concurrent.futures.ThreadPoolExecutor 有風險嗎?
問題陳述:
在提供的測試程式碼中,ThreadPoolExecutor 用於同時從多個網站擷取資料。令人擔憂的是,在 FastAPI 端點中使用此方法可能會導致過多的執行緒建立和資源匱乏和應用程式崩潰等潛在問題。
問題與潛在問題:
建議解決方案:使用 HTTPX 函式庫
建議使用 HTTPX 函式庫,而不是使用 ThreadPoolExecutor,它提供了非同步 API。 HTTPX 提供了許多優點:
工作範例:
from fastapi import FastAPI, Request from contextlib import asynccontextmanager import httpx import asyncio URLS = ['https://www.foxnews.com/', 'https://edition.cnn.com/', 'https://www.nbcnews.com/', 'https://www.bbc.co.uk/', 'https://www.reuters.com/'] @asynccontextmanager async def lifespan(app: FastAPI): # Customise settings limits = httpx.Limits(max_keepalive_connections=5, max_connections=10) timeout = httpx.Timeout(5.0, read=15.0) # 5s timeout on all operations # Initialise the Client on startup and add it to the state async with httpx.AsyncClient(limits=limits, timeout=timeout) as client: yield {'client': client} # The Client closes on shutdown app = FastAPI(lifespan=lifespan) async def send(url, client): return await client.get(url) @app.get('/') async def main(request: Request): client = request.state.client tasks = [send(url, client) for url in URLS] responses = await asyncio.gather(*tasks) return [r.text[:50] for r in responses] # For demo purposes, only return the first 50 chars of each response
此程式碼片段示範如何使用HTTPX 和FastAPI 來非同步處理並發請求,有效緩解與執行緒耗盡和資源爭用相關的問題。
以上是在 FastAPI 端點使用 `concurrent.futures.ThreadPoolExecutor` 有風險嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!