27 lines
659 B
Python
27 lines
659 B
Python
"""Request-scoped dependencies shared by the routers."""
|
|
from __future__ import annotations
|
|
|
|
import psycopg
|
|
from fastapi import HTTPException, Request
|
|
|
|
from .auth import Ctx
|
|
from .config import Config
|
|
from .db import connect
|
|
|
|
|
|
def get_cfg(request: Request) -> Config:
|
|
return request.app.state.cfg
|
|
|
|
|
|
def get_ctx(request: Request):
|
|
cfg: Config = request.app.state.cfg
|
|
try:
|
|
conn = connect(cfg)
|
|
except psycopg.Error:
|
|
# A transient DB outage must degrade to 503, not kill the server.
|
|
raise HTTPException(503, "database unavailable, try again shortly")
|
|
try:
|
|
yield Ctx(cfg, conn)
|
|
finally:
|
|
conn.close()
|