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
# For now, just return the same data and show metric usage
logger.debug(f"Metric used: {metric}")
client = request.app.requests_client
__aggregates = await get_data_from_ontap(client, logger, "172.16.57.2", "admin", "Netapp12", "storage/aggregates", "fields=name,uuid,space,node,home_node")
__aggregates = await get_data_from_ontap(request, logger, "172.16.57.2", "admin", "Netapp12", "storage/aggregates", "fields=name,uuid,space,node,home_node")
logger.debug(__aggregates)
__aggregates = __aggregates.get("records")
if metric == MetricEnum.relative:

View File

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

View File

@@ -1,6 +1,8 @@
import logging
from fastapi import Request
import httpx
def round_bytes(size_in_bytes: int) -> str:
# Helper function to convert bytes to a human-readable format
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"
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}"
if query_string:
url += f"?{query_string}"
async with client as _client:
async with request.state.requests_client as _client:
try:
logger.debug(f"Fetching data from ONTAP: {url}")
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}")
return None
def setup_logging() -> None:
"""Configure logging for the application"""
logging.basicConfig(
level=logging.DEBUG,
format="[%(asctime)s] [%(levelname)5s] %(message)s"
)
logging.basicConfig(level=logging.DEBUG, format="[%(asctime)s] [%(levelname)5s] %(message)s")
print(f"Logger is initialized.")