Skip to content

feat(core): inicialización de Flask Foundation, Application Factory y dependencias base#3

Merged
Ochoa-Stack merged 7 commits into
developfrom
feature/flask-foundation
Jun 6, 2026
Merged

feat(core): inicialización de Flask Foundation, Application Factory y dependencias base#3
Ochoa-Stack merged 7 commits into
developfrom
feature/flask-foundation

Conversation

@Ochoa-Stack

Copy link
Copy Markdown
Owner

feature/flask-foundation

Descripción

Se establece la fundación ejecutable del backend configurando el núcleo de Flask y sus extensiones. Este PR levanta el entorno de desarrollo y asegura que la aplicación pueda arrancar localmente sin dependencias circulares, implementando el patrón Application Factory.

Principales cambios estructurales:

  1. Gestión de Entornos: Configuración separada y basada en .env (Development, Production, Testing) controlada vía mapa en app/config.py.
  2. Dependencias: Definición explícita en requirements.txt y requirements-dev.txt (Flask 3.1+, SQLAlchemy, JWT, CORS, APScheduler, spaCy, pandas).
  3. Application Factory (app/__init__.py):
    • Inicialización controlada de la app (load_dotenv, selección de entorno).
    • Manejo defensivo en producción: RuntimeError si DATABASE_URL no existe.
    • Centralización y formato uniforme (JSON) para respuestas de error de API y JWT.
    • Endpoint /api/health habilitado.
  4. Fronteras Lógicas: Instanciación limpia de extensiones en extensions.py (evitando importaciones circulares) y creación de stubs de Blueprints para auth, panorama, alerts y admin.
  5. Entry Point: Archivo run.py configurado exclusivamente para uso en desarrollo local.

Nota de parche (Sub-ronda 4.5.1 integrada): Se reubicó la validación estricta de DATABASE_URL de la clase ProductionConfig hacia la función create_app() para evitar colapsos al importar el módulo en entornos locales.

Tipo de cambio

  • feat
  • fix
  • refactor
  • chore
  • docs
  • test

Cómo probar

  1. Tras el merge a develop, sincronizar localmente: git checkout develop && git pull origin develop
  2. Posicionarse en la carpeta del backend: cd backend
  3. Crear y activar un entorno virtual: python -m venv .venv, .venv\Scripts\Activate.ps1 (en Windows).
  4. Instalar las dependencias de desarrollo: pip install -r requirements-dev.txt (spacy y pandas pueden tomar tiempo).
  5. Copiar la plantilla de entorno: cp .env.example .env (no es necesario modificar valores por ahora).
  6. Arrancar la aplicación: python run.py.
  7. En otra terminal o navegador, verificar el endpoint de salud: curl http://localhost:5000/api/health. Debería responder con:
    {
      "status": "ok",
      "service": "SkillStat API"
    }

Copilot AI review requested due to automatic review settings June 6, 2026 03:29

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Este PR establece la base ejecutable del backend con Flask aplicando el patrón Application Factory, separando configuración por entorno y creando la infraestructura mínima (extensiones, blueprints stubs, endpoint de healthcheck) para arrancar localmente sin dependencias circulares.

Changes:

  • Se implementa create_app() con registro de extensiones, blueprints, handlers de error JSON y /api/health.
  • Se introduce configuración por entornos (development/production/testing) y plantilla .env.example.
  • Se definen dependencias base y de desarrollo (pytest, flake8/black/isort, bandit, etc.).

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
backend/run.py Entry point de desarrollo que instancia la app vía factory.
backend/requirements.txt Dependencias de runtime (Flask, SQLAlchemy, JWT, CORS, etc.).
backend/requirements-dev.txt Dependencias de dev (tests, lint/format, bandit, httpie).
backend/app/extensions.py Instancias de extensiones Flask para inicialización desacoplada.
backend/app/controllers/auth_bp.py Stub de blueprint de autenticación.
backend/app/controllers/panorama_bp.py Stub de blueprint de panorama.
backend/app/controllers/alerts_bp.py Stub de blueprint de alertas.
backend/app/controllers/admin_bp.py Stub de blueprint de administración.
backend/app/config.py Clases de configuración por entorno y config_map.
backend/app/init.py Application Factory, registro de extensiones/blueprints/errores/healthcheck.
backend/.env.example Plantilla de variables de entorno para desarrollo.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/app/__init__.py
Comment on lines +4 to +22
from flask import Flask, jsonify
from dotenv import load_dotenv

from app.config import config_map
from app.extensions import db, jwt, cors, migrate


def create_app(env: str = None) -> Flask:
"""Crea y configura una instancia de la aplicación Flask"""

# Cargamos las variables de entorno antes de leer cualquier configuración para que estén disponibles cuando se instancian las clases de config
load_dotenv()

app = Flask(__name__, instance_relative_config=False)

# Seleccionamos la configuración según el entorno
env = env or os.environ.get("FLASK_ENV", "development")
config_class = config_map.get(env, config_map["development"])
app.config.from_object(config_class)
Comment thread backend/app/__init__.py
Comment on lines +24 to +30
# Verificamos que la base de datos esté configurada antes de continuar
# Hacemos esta validación aquí y no en la clase de configuración para que ocurra en tiempo de ejecución real y solo cuando el entorno es producción
if env == "production" and not app.config.get("SQLALCHEMY_DATABASE_URI"):
raise RuntimeError(
"DATABASE_URL no está definida. "
"La aplicación no puede iniciar en producción sin una base de datos configurada."
)
Comment thread backend/app/config.py
Comment on lines +28 to +30
CORS_ORIGINS = os.environ.get(
"CORS_ORIGINS", "http://localhost:5500"
).split(",")
Comment thread backend/app/config.py
seconds=int(os.environ.get("JWT_ACCESS_TOKEN_EXPIRES", 86400))
)

JWT_ERROR_MESSAGE_KEY = "error"
Comment thread backend/app/__init__.py
Comment on lines +93 to +96
app.register_blueprint(auth_bp, url_prefix="/api/auth")
app.register_blueprint(panorama_bp, url_prefix="/api/panorama")
app.register_blueprint(alerts_bp, url_prefix="/api/alerts")
app.register_blueprint(admin_bp, url_prefix="/api/admin")
Comment thread backend/app/__init__.py
Comment on lines +181 to +185
return jsonify({
"status": "ok",
"service": "SkillStat API",
}), 200

No newline at end of file
Comment thread backend/run.py
Comment on lines +13 to +14
)

No newline at end of file
@Ochoa-Stack Ochoa-Stack merged commit 3d0df2d into develop Jun 6, 2026
1 check passed
@Ochoa-Stack Ochoa-Stack deleted the feature/flask-foundation branch June 6, 2026 03:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants