Estructura inicial funcional con documentación en el README.md de la FastAPI
This commit is contained in:
66
app/main.py
Normal file
66
app/main.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""Punto de entrada de la API. Ejecutar: uvicorn app.main:app --host 0.0.0.0 --port 8000"""
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import init_db
|
||||
from app.routers import archivos, descargas
|
||||
from app import elastic
|
||||
from app.storage import get_storage
|
||||
|
||||
|
||||
def configurar_logs() -> None:
|
||||
ruta = Path(get_settings().log_file)
|
||||
ruta.parent.mkdir(parents=True, exist_ok=True)
|
||||
handler = RotatingFileHandler(ruta, maxBytes=5_000_000, backupCount=5, encoding="utf-8")
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
|
||||
for nombre in ("api", "indexador"):
|
||||
logger = logging.getLogger(nombre)
|
||||
logger.setLevel(logging.INFO)
|
||||
if not logger.handlers:
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
configurar_logs()
|
||||
s = get_settings()
|
||||
if "cambiar" in s.jwt_secret or "cambiar" in s.download_secret:
|
||||
logging.getLogger("api").warning("JWT_SECRET/DOWNLOAD_SECRET tienen el valor de ejemplo: cambialos en el .env")
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="API de archivos por persona", version="1.0.0", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=get_settings().origenes_cors,
|
||||
allow_methods=["GET"],
|
||||
allow_headers=["Authorization"],
|
||||
)
|
||||
|
||||
app.include_router(archivos.router)
|
||||
app.include_router(descargas.router)
|
||||
|
||||
|
||||
@app.get("/salud", tags=["sistema"])
|
||||
def salud():
|
||||
"""Para monitoreo: confirma que la API responde, que Elasticsearch contesta
|
||||
(búsquedas) y que la carpeta de archivos es accesible (descargas)."""
|
||||
try:
|
||||
accesible = get_storage().disponible()
|
||||
except Exception: # noqa: BLE001 - ej. carpeta no montada
|
||||
accesible = False
|
||||
buscador = elastic.disponible()
|
||||
return {
|
||||
"estado": "ok" if accesible and buscador else "degradado",
|
||||
"elasticsearch_accesible": buscador,
|
||||
"tipo_almacenamiento": get_settings().storage_type,
|
||||
"almacenamiento_accesible": accesible,
|
||||
}
|
||||
Reference in New Issue
Block a user