make shared connections available via request.shared.XXX

This commit is contained in:
Magel, Denis
2025-09-18 15:28:50 +02:00
parent 58f7c5c393
commit b60383071a
3 changed files with 8 additions and 10 deletions

View File

@@ -16,8 +16,7 @@ async def get_aggregates(request: Request, metric: str = "relative") -> List[Agg
# You can use the metric parameter to filter or modify results as needed # You can use the metric parameter to filter or modify results as needed
# For now, just return the same data and show metric usage # For now, just return the same data and show metric usage
logger.debug(f"Metric used: {metric}") logger.debug(f"Metric used: {metric}")
client = request.app.requests_client __aggregates = await get_data_from_ontap(request, logger, "172.16.57.2", "admin", "Netapp12", "storage/aggregates", "fields=name,uuid,space,node,home_node")
__aggregates = await get_data_from_ontap(client, logger, "172.16.57.2", "admin", "Netapp12", "storage/aggregates", "fields=name,uuid,space,node,home_node")
logger.debug(__aggregates) logger.debug(__aggregates)
__aggregates = __aggregates.get("records") __aggregates = __aggregates.get("records")
if metric == MetricEnum.relative: if metric == MetricEnum.relative:

View File

@@ -20,7 +20,6 @@ logger.setLevel("DEBUG")
logger.info("Starting application") logger.info("Starting application")
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
"""make loading it async""" """make loading it async"""
@@ -39,7 +38,7 @@ async def lifespan(app: FastAPI):
log.error("Configuration initialization failed. Exiting...") log.error("Configuration initialization failed. Exiting...")
# exit(1) # exit(1)
requests_client = httpx.AsyncClient(verify=False) requests_client = httpx.AsyncClient(verify=False)
yield yield {"redis_conn": shared_redis_conn, "requests_client": requests_client}
await requests_client.aclose() await requests_client.aclose()
log.info("Shutting down FastAPI app...") log.info("Shutting down FastAPI app...")

View File

@@ -1,6 +1,8 @@
import logging import logging
from fastapi import Request
import httpx import httpx
def round_bytes(size_in_bytes: int) -> str: def round_bytes(size_in_bytes: int) -> str:
# Helper function to convert bytes to a human-readable format # Helper function to convert bytes to a human-readable format
for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]: for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]:
@@ -10,11 +12,11 @@ def round_bytes(size_in_bytes: int) -> str:
return f"{size_in_bytes:.2f}EB" return f"{size_in_bytes:.2f}EB"
async def get_data_from_ontap(client, logger, hostname: str, username: str, password: str, endpoint: str, query_string: str = ""): async def get_data_from_ontap(request: Request, logger, hostname: str, username: str, password: str, endpoint: str, query_string: str = ""):
url = f"https://{hostname}/api/{endpoint}" url = f"https://{hostname}/api/{endpoint}"
if query_string: if query_string:
url += f"?{query_string}" url += f"?{query_string}"
async with client as _client: async with request.state.requests_client as _client:
try: try:
logger.debug(f"Fetching data from ONTAP: {url}") logger.debug(f"Fetching data from ONTAP: {url}")
response = await _client.get(url, auth=(username, password)) response = await _client.get(url, auth=(username, password))
@@ -24,10 +26,8 @@ async def get_data_from_ontap(client, logger, hostname: str, username: str, pass
logger.error(f"HTTP error occurred: {e}") logger.error(f"HTTP error occurred: {e}")
return None return None
def setup_logging() -> None: def setup_logging() -> None:
"""Configure logging for the application""" """Configure logging for the application"""
logging.basicConfig( logging.basicConfig(level=logging.DEBUG, format="[%(asctime)s] [%(levelname)5s] %(message)s")
level=logging.DEBUG,
format="[%(asctime)s] [%(levelname)5s] %(message)s"
)
print(f"Logger is initialized.") print(f"Logger is initialized.")