Some checks failed
Run linters on applied template / Python 3.13 lint and build (push) Failing after 42s
This is a FastAPI backend microservice template used with `copier` utility. Features of applied template are: - Configuration file processing logic - Metrics and tracing (both optional) configuration available - Debug endpoints - Database migration commands, prepared Alembic environment - Database usage example in ping_db endpoint - gitea sanity check pipeline
34 lines
1.3 KiB
Python
34 lines
1.3 KiB
Python
"""PostgresConnectionManager dependency functions are defined here."""
|
|
|
|
from fastapi import FastAPI, Request
|
|
from structlog.stdlib import BoundLogger
|
|
|
|
|
|
def init_dispencer(app: FastAPI, logger: BoundLogger) -> None:
|
|
"""Initialize BoundLogger dispencer at app's state."""
|
|
if hasattr(app.state, "logger"):
|
|
if not isinstance(app.state.logger, BoundLogger):
|
|
raise ValueError("logger attribute of app's state is already set" f"with other value ({app.state.logger})")
|
|
return
|
|
|
|
app.state.logger = logger
|
|
|
|
|
|
def attach_to_request(request: Request, logger: BoundLogger) -> None:
|
|
"""Set logger for a concrete request. If request had already had a logger, replace it."""
|
|
if hasattr(request.state, "logger"):
|
|
if not isinstance(request.state.logger, BoundLogger):
|
|
logger.warning("request.state.logger is already set with other value", value=request.state.logger)
|
|
request.state.logger = logger
|
|
|
|
|
|
def obtain(request: Request) -> BoundLogger:
|
|
"""Get a logger from request or app state."""
|
|
if hasattr(request.state, "logger"):
|
|
logger = request.state.logger
|
|
if isinstance(logger, BoundLogger):
|
|
return logger
|
|
if not hasattr(request.app.state, "logger"):
|
|
raise ValueError("BoundLogger dispencer was not initialized at app preparation")
|
|
return request.app.state.logger
|