Refactored code completely, to work better!

This commit is contained in:
Lutchy Horace 2025-04-02 17:39:25 -04:00
parent 7be4d3a0f4
commit cc46a77800

View file

@ -1,6 +1,6 @@
from fastapi import FastAPI, Request, Response from fastapi import FastAPI, Request, Response
import redis import redis
import httpx import aiohttp
import os import os
import logging import logging
@ -62,36 +62,42 @@ async def proxy_request(path: str, request: Request):
</Error>""" </Error>"""
return Response(content=error_xml, status_code=403, media_type="application/xml") 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}" minio_url = f"{MINIO_ENDPOINT}/{path}"
if query_string:
minio_url += f"?{query_string}"
headers = dict(request.headers) headers = dict(request.headers)
async with httpx.AsyncClient(timeout=300.0) as client: try:
logging.info(f"Proxying request to MinIO: {minio_url}") async with aiohttp.ClientSession() as session:
if request.method in ["PUT", "POST"]: async with session.request(
# Stream request body to MinIO
async def request_stream():
async for chunk in request.stream():
yield chunk
minio_response = await client.request(
method=request.method, method=request.method,
url=minio_url, url=minio_url,
headers=headers, headers=headers,
content=request_stream() data=request.stream() if request.method in ["PUT", "POST"] else None
) ) as minio_response:
else:
# For GET and DELETE, we dont send a body # Try reading the response body
minio_response = await client.request( try:
method=request.method, body = await minio_response.read()
url=minio_url, except aiohttp.ClientConnectionError:
headers=headers 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( except aiohttp.ClientConnectionError:
content=minio_response.content, return Response(content=b"", status_code=200) # Silently ignore MinIO disconnection
status_code=minio_response.status_code,
headers=minio_response.headers 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)