Download app/main.py from Modulo-6/api: direct link, hf CLI and curl.
- Browser
- Download file 5.14 kB
-
https://huggingface.co/spaces/Modulo-6/api/resolve/abb37522de5ae43d93dfdca315ce81b830ce312c/app/main.py
- Command line
-
hf download hf://spaces/Modulo-6/api@abb37522de5ae43d93dfdca315ce81b830ce312c/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Modulo-6/api/resolve/abb37522de5ae43d93dfdca315ce81b830ce312c/app/main.py
5.14 kB
| """ | |
| Health Grid - Módulo 6: Internación y Gestión de Camas | |
| API REST: http://localhost:8006/api/v1 | |
| """ | |
| import asyncio | |
| import contextlib | |
| import logging | |
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI, Request, status | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| from app.config import settings | |
| from app.dependencies import create_access_token | |
| from app.integrations import rabbit_consumer | |
| from app.routers import auth, camas, quirofanos, solicitudes, webhooks, auditoria | |
| from app.routers.webhooks import router_turnos | |
| logger = logging.getLogger(__name__) | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s %(levelname)s %(name)s: %(message)s", | |
| ) | |
| # ─── Startup / Shutdown ──────────────────────────────────────────────────── | |
| async def lifespan(app: FastAPI): | |
| logger.info("Conectado a Supabase — listo para operar") | |
| consumer_task = None | |
| if settings.rabbitmq_consumer_enabled: | |
| logger.info("Iniciando consumer de %s", settings.internacion_requests_queue) | |
| consumer_task = asyncio.create_task(rabbit_consumer.run_consumer()) | |
| yield | |
| if consumer_task is not None: | |
| consumer_task.cancel() | |
| with contextlib.suppress(asyncio.CancelledError): | |
| await consumer_task | |
| # ─── App ─────────────────────────────────────────────────────────────────── | |
| app = FastAPI( | |
| title="Health Grid – Módulo 6: Internación y Gestión de Camas", | |
| description="API REST para gestión de camas hospitalarias y solicitudes de internación.", | |
| version="4.0.0", | |
| lifespan=lifespan, | |
| docs_url="/api/v1/docs", | |
| redoc_url="/api/v1/redoc", | |
| openapi_url="/api/v1/openapi.json", | |
| ) | |
| # Cometario pra tests | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=settings.allowed_origins, | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # ─── Prefijo global /api/v1 ──────────────────────────────────────────────── | |
| PREFIX = "/api/v1" | |
| app.include_router(auth.router, prefix=PREFIX) | |
| app.include_router(camas.router, prefix=PREFIX) | |
| app.include_router(quirofanos.router, prefix=PREFIX) | |
| app.include_router(solicitudes.router, prefix=PREFIX) | |
| app.include_router(webhooks.router, prefix=PREFIX) | |
| app.include_router(router_turnos, prefix=PREFIX) | |
| app.include_router(auditoria.router, prefix=PREFIX) | |
| # ─── Endpoint de auth local (mock de M10 — solo para desarrollo) ─────────── | |
| def get_dev_token(usuario: str, password: str): | |
| """ | |
| Solo habilitado si ENVIRONMENT=development. | |
| Genera un JWT de prueba (el mismo formato HS256 que emite el canje SSO, | |
| ver `app/routers/auth.py`). Roles válidos: ADMINISTRATIVO | MEDICO | LIMPIEZA | |
| Alternativa con el Core real (M10): loguearse ahí, obtener un ticket SSO | |
| (`POST /auth/sso-ticket`) y canjearlo en `POST /api/v1/auth/sso-exchange`. | |
| """ | |
| if settings.environment != "development": | |
| return JSONResponse( | |
| status_code=404, | |
| content={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Not Found"}, | |
| ) | |
| roles_validos = {"ADMINISTRATIVO", "MEDICO", "LIMPIEZA"} | |
| rol = usuario.upper() | |
| if rol not in roles_validos: | |
| return JSONResponse( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| content={ | |
| "codigo": "NO_AUTENTICADO", | |
| "mensaje": f"Rol inválido. Usar: {roles_validos}", | |
| }, | |
| ) | |
| token = create_access_token(sub="1", rol=rol) | |
| return {"access_token": token, "token_type": "bearer", "rol": rol} | |
| # ─── Health check ────────────────────────────────────────────────────────── | |
| def health(): | |
| return {"status": "ok", "module": "M6 - Internación "} | |
| # ─── Manejadores de errores globales ─────────────────────────────────────── | |
| async def not_found_handler(request: Request, exc: Exception): | |
| return JSONResponse( | |
| status_code=404, | |
| content={ | |
| "codigo": "RECURSO_NO_ENCONTRADO", | |
| "mensaje": "El recurso solicitado no existe", | |
| }, | |
| ) | |
| async def method_not_allowed_handler(request: Request, exc: Exception): | |
| return JSONResponse( | |
| status_code=405, | |
| content={ | |
| "codigo": "METODO_NO_PERMITIDO", | |
| "mensaje": "Método HTTP no permitido", | |
| }, | |
| ) | |