Skip to content

Commit 224d297

Browse files
feat: Reuse shared async HTTP client for proxy requests
1 parent 35b31d8 commit 224d297

1 file changed

Lines changed: 12 additions & 5 deletions

File tree

‎app/main.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,15 @@
66
from fastapi import Request
77
from app.database import SessionLocal
88
from app.models import RequestLog
9+
from contextlib import asynccontextmanager
910

10-
app = FastAPI()
11+
@asynccontextmanager
12+
async def lifespan(app: FastAPI):
13+
app.state.http_client = httpx.AsyncClient(timeout=5.0)
14+
yield
15+
await app.state.http_client.aclose()
16+
17+
app = FastAPI(lifespan=lifespan)
1118
app.state.buckets = {}
1219
app.state.session_factory = SessionLocal
1320

@@ -16,16 +23,16 @@ def health():
1623
return {"status": "ok"}
1724

1825
@app.get("/proxy")
19-
async def proxy(_: APIKey = Depends(enforce_rate_limit)):
26+
async def proxy(request: Request, _: APIKey = Depends(enforce_rate_limit)):
2027
try:
21-
async with httpx.AsyncClient(timeout=5.0) as client:
22-
r = await client.get('https://httpbin.org/get')
23-
return r.json()
28+
r = await request.app.state.http_client.get("https://httpbin.org/get")
29+
return r.json()
2430
except httpx.TimeoutException:
2531
raise HTTPException(status_code=504, detail="Gateway timeout")
2632
except httpx.RequestError:
2733
raise HTTPException(status_code=502, detail="Bad gateway")
2834

35+
2936
@app.middleware("http")
3037
async def log_proxy_requests(request: Request, call_next):
3138
if request.url.path != "/proxy":

0 commit comments

Comments
 (0)