在 FastAPI 端点中使用 Concurrent.futures.ThreadPoolExecutor 有风险吗?
问题陈述:
在提供的测试代码中, ThreadPoolExecutor 用于同时从多个网站检索数据。令人担忧的是,在 FastAPI 端点中使用此方法可能会导致过多的线程创建和资源匮乏和应用程序崩溃等潜在问题。
问题和潜在问题:
推荐解决方案:使用 HTTPX 库
建议使用提供异步 API 的 HTTPX 库,而不是使用 ThreadPoolExecutor。 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中文网其他相关文章!