feat(core): inicialización de Flask Foundation, Application Factory y dependencias base#3
Merged
Merged
Conversation
There was a problem hiding this comment.
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 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 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 on lines
+28
to
+30
| CORS_ORIGINS = os.environ.get( | ||
| "CORS_ORIGINS", "http://localhost:5500" | ||
| ).split(",") |
| seconds=int(os.environ.get("JWT_ACCESS_TOKEN_EXPIRES", 86400)) | ||
| ) | ||
|
|
||
| JWT_ERROR_MESSAGE_KEY = "error" |
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 on lines
+181
to
+185
| return jsonify({ | ||
| "status": "ok", | ||
| "service": "SkillStat API", | ||
| }), 200 | ||
|
No newline at end of file |
Comment on lines
+13
to
+14
| ) | ||
|
No newline at end of file |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
.env(Development, Production, Testing) controlada vía mapa enapp/config.py.requirements.txtyrequirements-dev.txt(Flask 3.1+, SQLAlchemy, JWT, CORS, APScheduler, spaCy, pandas).app/__init__.py):RuntimeErrorsiDATABASE_URLno existe./api/healthhabilitado.extensions.py(evitando importaciones circulares) y creación de stubs de Blueprints paraauth,panorama,alertsyadmin.run.pyconfigurado exclusivamente para uso en desarrollo local.Nota de parche (Sub-ronda 4.5.1 integrada): Se reubicó la validación estricta de
DATABASE_URLde la claseProductionConfighacia la funcióncreate_app()para evitar colapsos al importar el módulo en entornos locales.Tipo de cambio
Cómo probar
develop, sincronizar localmente:git checkout develop && git pull origin developcd backendpython -m venv .venv,.venv\Scripts\Activate.ps1(en Windows).pip install -r requirements-dev.txt(spacy y pandas pueden tomar tiempo).cp .env.example .env(no es necesario modificar valores por ahora).python run.py.curl http://localhost:5000/api/health. Debería responder con:{ "status": "ok", "service": "SkillStat API" }