Refactored code completely, to work better!
This commit is contained in:
parent
7be4d3a0f4
commit
cc46a77800
1 changed files with 32 additions and 26 deletions
|
@ -1,6 +1,6 @@
|
|||
from fastapi import FastAPI, Request, Response
|
||||
import redis
|
||||
import httpx
|
||||
import aiohttp
|
||||
import os
|
||||
import logging
|
||||
|
||||
|
@ -62,36 +62,42 @@ async def proxy_request(path: str, request: Request):
|
|||
</Error>"""
|
||||
return Response(content=error_xml, status_code=403, media_type="application/xml")
|
||||
|
||||
# Proxy request to MinIO
|
||||
query_string = request.url.query
|
||||
minio_url = f"{MINIO_ENDPOINT}/{path}"
|
||||
if query_string:
|
||||
minio_url += f"?{query_string}"
|
||||
headers = dict(request.headers)
|
||||
|
||||
async with httpx.AsyncClient(timeout=300.0) as client:
|
||||
logging.info(f"Proxying request to MinIO: {minio_url}")
|
||||
if request.method in ["PUT", "POST"]:
|
||||
# Stream request body to MinIO
|
||||
async def request_stream():
|
||||
async for chunk in request.stream():
|
||||
yield chunk
|
||||
|
||||
minio_response = await client.request(
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.request(
|
||||
method=request.method,
|
||||
url=minio_url,
|
||||
headers=headers,
|
||||
content=request_stream()
|
||||
)
|
||||
else:
|
||||
# For GET and DELETE, we don’t send a body
|
||||
minio_response = await client.request(
|
||||
method=request.method,
|
||||
url=minio_url,
|
||||
headers=headers
|
||||
)
|
||||
data=request.stream() if request.method in ["PUT", "POST"] else None
|
||||
) as minio_response:
|
||||
|
||||
# Try reading the response body
|
||||
try:
|
||||
body = await minio_response.read()
|
||||
except aiohttp.ClientConnectionError:
|
||||
body = b"" # If MinIO closes connection, return an empty response
|
||||
|
||||
logging.info(f"MinIO response: {minio_response.status_code}")
|
||||
# Forward MinIO's response as-is
|
||||
return Response(
|
||||
content=body,
|
||||
status_code=minio_response.status,
|
||||
headers=dict(minio_response.headers)
|
||||
)
|
||||
|
||||
return Response(
|
||||
content=minio_response.content,
|
||||
status_code=minio_response.status_code,
|
||||
headers=minio_response.headers
|
||||
)
|
||||
except aiohttp.ClientConnectionError:
|
||||
return Response(content=b"", status_code=200) # Silently ignore MinIO disconnection
|
||||
|
||||
except aiohttp.ClientResponseError as e:
|
||||
return Response(content=e.message, status_code=e.status)
|
||||
|
||||
except aiohttp.ClientError:
|
||||
return Response(content="An error occurred while communicating with MinIO.", status_code=502)
|
||||
|
||||
except Exception:
|
||||
return Response(content="Internal Server Error", status_code=500)
|
||||
|
|
Loading…
Add table
Reference in a new issue