Skip to content

Commit 781a08e

Browse files
committed
refactor: use async context manager and improve error handling in reverse_proxy
1 parent 3de3c22 commit 781a08e

1 file changed

Lines changed: 24 additions & 17 deletions

File tree

  • backend/app/api/internal/endpoints

backend/app/api/internal/endpoints/proxy.py

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,21 +57,28 @@ async def reverse_proxy(request: Request) -> Response:
5757
"/internal/proxy/auto-acmg", ""
5858
)
5959

60-
if backend_url:
61-
client = httpx.AsyncClient()
62-
backend_url = backend_url + (f"?{url.query}" if url.query else "")
63-
backend_req = client.build_request(
64-
method=request.method,
65-
url=backend_url,
66-
headers=request.headers.raw,
67-
content=await request.body(),
68-
)
69-
backend_resp = await client.send(backend_req, stream=True)
70-
return StreamingResponse(
71-
backend_resp.aiter_raw(),
72-
status_code=backend_resp.status_code,
73-
headers=backend_resp.headers,
74-
background=BackgroundTasks([BackgroundTask(backend_resp.aclose)]),
75-
)
76-
else:
60+
if not backend_url:
7761
return Response(status_code=404, content="Reverse proxy route not found")
62+
63+
backend_url = backend_url + (f"?{url.query}" if url.query else "")
64+
65+
try:
66+
async with httpx.AsyncClient(timeout=10.0) as client:
67+
backend_req = client.build_request(
68+
method=request.method,
69+
url=backend_url,
70+
headers=request.headers.raw,
71+
content=await request.body(),
72+
)
73+
backend_resp = await client.send(backend_req, stream=True)
74+
except httpx.RequestError as exc:
75+
return Response(status_code=502, content=f"Proxy error: {str(exc)}")
76+
except Exception as exc:
77+
return Response(status_code=500, content=f"Unexpected error: {str(exc)}")
78+
79+
return StreamingResponse(
80+
backend_resp.aiter_raw(),
81+
status_code=backend_resp.status_code,
82+
headers=backend_resp.headers,
83+
background=BackgroundTasks([BackgroundTask(backend_resp.aclose)]),
84+
)

0 commit comments

Comments
 (0)