Два варианта использования httpx в FastAPI-эндпоинте. Какой правильный?
middle
correct_vs_wrong
#316
Вариант 1
# Создание клиента на каждый запрос
@app.get("/orders/{id}")
async def get_order(id: int):
async with httpx.AsyncClient(timeout=30.0) as client:
r = await client.get(f"http://orders/{id}")
return r.json()
Вариант 2
# Один клиент на жизнь приложения
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(
base_url="http://orders",
timeout=httpx.Timeout(5.0, read=30.0),
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
)
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
def get_http(request: Request) -> httpx.AsyncClient:
return request.app.state.http
@app.get("/orders/{id}")
async def get_order(id: int, http: httpx.AsyncClient = Depends(get_http)):
r = await http.get(f"/{id}")
return r.json()
Чтобы решить вопрос и сохранить попытку — войди.