feat(base): finalizada Fase 1 scaffolding v0.1.0-alpha
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
# ==============================================================================
|
||||
# Dockerfile para Backend FastAPI (OnEverControl)
|
||||
# Compatible con Linux x86_64 y ARM64
|
||||
# ==============================================================================
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Evitar prompts interactivos y buffer de python
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
# Instalar dependencias del sistema requeridas por FreeTDS (pymssql)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
freetds-dev \
|
||||
freetds-bin \
|
||||
build-essential \
|
||||
curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Configurar directorio de trabajo
|
||||
WORKDIR /app
|
||||
|
||||
# Copiar dependencias de Python e instalarlas
|
||||
COPY requirements.txt /app/
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copiar el código de la aplicación
|
||||
COPY app/ /app/app/
|
||||
|
||||
# Exponer el puerto de Uvicorn
|
||||
EXPOSE 8000
|
||||
|
||||
# Healthcheck interno de Docker
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||
CMD curl -f http://localhost:8000/health || exit 1
|
||||
|
||||
# Comando por defecto
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1 @@
|
||||
# OnEverControl Backend Package
|
||||
@@ -0,0 +1,6 @@
|
||||
# ==============================================================================
|
||||
# OnEverControl - Versión del Backend
|
||||
# ==============================================================================
|
||||
__version__ = "0.1.0-alpha"
|
||||
__app_name__ = "OnEverControl"
|
||||
__description__ = "Cliente Web Reducido para Puesto de Control en Red Local de OnEverAccess"
|
||||
@@ -0,0 +1 @@
|
||||
# API module
|
||||
@@ -0,0 +1 @@
|
||||
# API v1 module
|
||||
@@ -0,0 +1,11 @@
|
||||
# ==============================================================================
|
||||
# Router Principal API v1
|
||||
# ==============================================================================
|
||||
from fastapi import APIRouter
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
# En fases posteriores aquí se incluirán los sub-routers:
|
||||
# api_router.include_router(auth.router, prefix="/auth", tags=["Autenticación"])
|
||||
# api_router.include_router(control_posts.router, prefix="/control-posts", tags=["Puestos de Control"])
|
||||
# api_router.include_router(access.router, prefix="/access", tags=["Accesos"])
|
||||
@@ -0,0 +1 @@
|
||||
# Core module
|
||||
@@ -0,0 +1,66 @@
|
||||
# ==============================================================================
|
||||
# Configuración Tipada con Pydantic Settings
|
||||
# Compatible con Windows 10/11, LXC y Docker
|
||||
# ==============================================================================
|
||||
from pathlib import Path
|
||||
from typing import List, Union
|
||||
from pydantic import Field, field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
# Directorio raíz del proyecto (OnEverControl)
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent.parent
|
||||
ENV_PATH = BASE_DIR / ".env"
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=str(ENV_PATH) if ENV_PATH.exists() else None,
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
# Entorno
|
||||
ENVIRONMENT: str = "development"
|
||||
DEBUG: bool = True
|
||||
LOG_LEVEL: str = "INFO"
|
||||
|
||||
# Servidor
|
||||
SERVER_HOST: str = "0.0.0.0"
|
||||
SERVER_PORT: int = 8000
|
||||
ALLOWED_ORIGINS: Union[str, List[str]] = [
|
||||
"http://localhost:5173",
|
||||
"http://127.0.0.1:5173",
|
||||
"http://localhost:8000",
|
||||
"http://127.0.0.1:8000",
|
||||
]
|
||||
|
||||
# Base de Datos SQL Server (videoman)
|
||||
DB_SERVER: str = "127.0.0.1"
|
||||
DB_PORT: int = 1433
|
||||
DB_NAME: str = "videoman"
|
||||
DB_USER: str = "sa"
|
||||
DB_PASSWORD: str = ""
|
||||
DB_CHARSET: str = "CP1252"
|
||||
DB_TIMEOUT: int = 15
|
||||
|
||||
# Seguridad JWT
|
||||
SECRET_KEY: str = "dev_secret_key_change_in_production_min_32_chars_1234567890"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
|
||||
|
||||
# Estación por Defecto
|
||||
DEFAULT_WORKSTATION_NAME: str = "GARITA_PRINCIPAL"
|
||||
|
||||
@field_validator("ALLOWED_ORIGINS", mode="before")
|
||||
@classmethod
|
||||
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> List[str]:
|
||||
if isinstance(v, str) and not v.startswith("["):
|
||||
return [i.strip() for i in v.split(",") if i.strip()]
|
||||
elif isinstance(v, list):
|
||||
return v
|
||||
return ["*"]
|
||||
|
||||
|
||||
# Instancia singleton de configuración
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,64 @@
|
||||
# ==============================================================================
|
||||
# Punto de Entrada Principal FastAPI (OnEverControl)
|
||||
# ==============================================================================
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.__version__ import __version__, __app_name__, __description__
|
||||
from app.core.config import settings
|
||||
from app.api.v1.router import api_router
|
||||
|
||||
|
||||
# Creación de la instancia FastAPI
|
||||
app = FastAPI(
|
||||
title=__app_name__,
|
||||
version=__version__,
|
||||
description=__description__,
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# Middleware de Compresión GZip (optimiza transferencia a tablets por Wi-Fi)
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1000)
|
||||
|
||||
# Middleware de CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.ALLOWED_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health", tags=["Salud del Sistema"], summary="Verificar estado de salud del servicio")
|
||||
async def health_check():
|
||||
"""Retorna el estado de disponibilidad, versión y timestamp del servidor."""
|
||||
return JSONResponse(
|
||||
content={
|
||||
"status": "ok",
|
||||
"app": __app_name__,
|
||||
"version": __version__,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.get("/", tags=["Información"], summary="Información del servicio")
|
||||
async def root():
|
||||
"""Ruta raíz informativa."""
|
||||
return {
|
||||
"app": __app_name__,
|
||||
"version": __version__,
|
||||
"docs": "/docs",
|
||||
"health": "/health",
|
||||
"api_v1": "/api/v1",
|
||||
}
|
||||
|
||||
|
||||
# Montaje de routers versionados
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
@@ -0,0 +1,9 @@
|
||||
fastapi>=0.110.0
|
||||
uvicorn[standard]>=0.29.0
|
||||
pydantic>=2.7.0
|
||||
pydantic-settings>=2.2.0
|
||||
pymssql>=2.2.11
|
||||
python-multipart>=0.0.9
|
||||
httpx>=0.27.0
|
||||
pytest>=8.1.0
|
||||
pytest-asyncio>=0.23.0
|
||||
@@ -0,0 +1,30 @@
|
||||
import pytest
|
||||
from httpx import AsyncClient, ASGITransport
|
||||
from app.main import app
|
||||
from app.__version__ import __version__, __app_name__
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_health_check_returns_200_and_metadata():
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/health")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "ok"
|
||||
assert data["version"] == __version__
|
||||
assert data["app"] == __app_name__
|
||||
assert "timestamp" in data
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_root_redirects_or_returns_info():
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["app"] == __app_name__
|
||||
assert data["docs"] == "/docs"
|
||||
Reference in New Issue
Block a user