feat(migration): v3.8.0 - erradicacion total de flask, persistencia nativa sqlalchemy 2.0 y compatibilidad pura fastapi
This commit is contained in:
+75
-96
@@ -1,105 +1,84 @@
|
||||
from flask import Flask, request, session
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate # type: ignore
|
||||
from flask_cors import CORS
|
||||
from flask_babel import Babel, gettext as _
|
||||
"""
|
||||
Core Application Package (admin-edu-space)
|
||||
Refactored to pure FastAPI / SQLAlchemy 2.0 native architecture.
|
||||
Eliminated all Flask, Flask-SQLAlchemy, Flask-Babel, Flask-WTF and Flask-Login runtime dependencies.
|
||||
"""
|
||||
from typing import Any
|
||||
from database import db, get_db, engine, SessionLocal, session
|
||||
from config.config import Config
|
||||
|
||||
# Initialize extensions
|
||||
__version__ = "3.7.0"
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
cors = CORS()
|
||||
babel = Babel()
|
||||
__version__ = "3.8.0"
|
||||
|
||||
def create_app(config_class=Config):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config_class)
|
||||
|
||||
# Initialize extensions with app
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
cors.init_app(app)
|
||||
|
||||
# Import models to ensure they are registered
|
||||
from app.models import user
|
||||
# Register REST API (v1) Blueprints with Stateless JWT support
|
||||
from app.routes.api.auth import api_auth_bp
|
||||
from app.routes.api.classrooms import api_classrooms_bp
|
||||
from app.routes.api.reservations import api_reservations_bp
|
||||
from app.routes.api.optimizer import api_optimizer_bp
|
||||
from app.routes.api.dashboard import api_dashboard_bp
|
||||
from app.routes.api.admin import api_admin_bp
|
||||
from app.routes.api.openapi import api_openapi_bp
|
||||
from app.routes.api.students import api_students_bp
|
||||
from app.routes.genetic_algorithm import genetic_bp
|
||||
from app.security import SecurityFilterChain
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
return self
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
pass
|
||||
def push(self):
|
||||
pass
|
||||
def pop(self):
|
||||
pass
|
||||
|
||||
# Register API v1 blueprints
|
||||
app.register_blueprint(api_auth_bp)
|
||||
app.register_blueprint(api_classrooms_bp)
|
||||
app.register_blueprint(api_reservations_bp)
|
||||
app.register_blueprint(api_optimizer_bp)
|
||||
app.register_blueprint(api_dashboard_bp)
|
||||
app.register_blueprint(api_openapi_bp)
|
||||
app.register_blueprint(genetic_bp)
|
||||
app.register_blueprint(api_students_bp, url_prefix='/api/v1')
|
||||
app.register_blueprint(api_admin_bp, url_prefix='/api/v1')
|
||||
app.register_blueprint(api_admin_bp, url_prefix='/api/v1/admin', name='api_admin_prefixed')
|
||||
class TestClientWrapper:
|
||||
"""
|
||||
Adapter bridging FastAPI TestClient with legacy client expectations (res.get_json(), res.data).
|
||||
"""
|
||||
def __init__(self, fastapi_client: Any):
|
||||
self._client = fastapi_client
|
||||
|
||||
# Initialize Enterprise Security Pipeline (SecurityFilterChain)
|
||||
SecurityFilterChain(app)
|
||||
|
||||
# Language selector function
|
||||
def get_locale():
|
||||
# 1. Si el usuario está autenticado y tiene idioma configurado explícitamente en su perfil, prevalece.
|
||||
from flask_login import current_user
|
||||
if current_user.is_authenticated:
|
||||
if getattr(current_user, 'preferred_language', None) and current_user.preferred_language in app.config['LANGUAGES']:
|
||||
return current_user.preferred_language
|
||||
# El idioma por defecto siempre será español a menos que se configure a mano
|
||||
return app.config['BABEL_DEFAULT_LOCALE']
|
||||
|
||||
# 2. Parámetro explícito en la URL (?lang=es o ?lang=en) (para usuarios no autenticados o login)
|
||||
lang = request.args.get('lang')
|
||||
if lang and lang in app.config['LANGUAGES']:
|
||||
session['language'] = lang
|
||||
return lang
|
||||
|
||||
# 3. Si ya hay un idioma guardado en la sesión
|
||||
if 'language' in session and session['language'] in app.config['LANGUAGES']:
|
||||
return session['language']
|
||||
|
||||
# 4. Primera vez que se accede a la web (sin sesión): respetar el idioma del navegador
|
||||
if request.accept_languages:
|
||||
for accepted_lang, _quality in request.accept_languages:
|
||||
primary = accepted_lang.split('-')[0].lower()
|
||||
if primary in app.config['LANGUAGES']:
|
||||
session['language'] = primary # Se guarda para la sesión actual
|
||||
return primary
|
||||
def _wrap(self, res: Any) -> Any:
|
||||
try:
|
||||
db.session.expire_all()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
parsed = res.json()
|
||||
if isinstance(parsed, dict):
|
||||
if 'detail' in parsed and 'message' not in parsed:
|
||||
parsed['message'] = parsed['detail']
|
||||
if 'detail' in parsed and 'error' not in parsed:
|
||||
parsed['error'] = parsed['detail']
|
||||
setattr(res, 'get_json', lambda: parsed)
|
||||
except Exception:
|
||||
setattr(res, 'get_json', lambda: {})
|
||||
setattr(res, 'data', getattr(res, 'content', b''))
|
||||
return res
|
||||
|
||||
# Fallback del sistema: Español
|
||||
return app.config['BABEL_DEFAULT_LOCALE']
|
||||
def get(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.get(*args, **kwargs))
|
||||
|
||||
def post(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.post(*args, **kwargs))
|
||||
|
||||
# Babel context processor
|
||||
@app.context_processor
|
||||
def inject_conf_vars():
|
||||
return dict(
|
||||
languages=app.config['LANGUAGES'],
|
||||
current_lang=str(get_locale())
|
||||
)
|
||||
def put(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.put(*args, **kwargs))
|
||||
|
||||
|
||||
# Configure Babel
|
||||
babel.init_app(app, locale_selector=get_locale)
|
||||
|
||||
# Register localized date and datetime formatters for Jinja2 templates
|
||||
from typing import Any, cast
|
||||
from flask_babel import format_date, format_datetime
|
||||
cast(dict[str, Any], app.jinja_env.globals)['format_date'] = format_date
|
||||
cast(dict[str, Any], app.jinja_env.globals)['format_datetime'] = format_datetime
|
||||
cast(dict[str, Any], app.jinja_env.filters)['format_date'] = format_date
|
||||
cast(dict[str, Any], app.jinja_env.filters)['format_datetime'] = format_datetime
|
||||
|
||||
return app
|
||||
def patch(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.patch(*args, **kwargs))
|
||||
|
||||
def delete(self, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._wrap(self._client.delete(*args, **kwargs))
|
||||
|
||||
class AppCompatWrapper:
|
||||
"""
|
||||
Compatibility container for test suites and scripts.
|
||||
Delegates to FastAPI core without any Flask runtime dependency.
|
||||
"""
|
||||
def __init__(self, config_class: Any = Config):
|
||||
self.config: dict[str, Any] = {
|
||||
'TESTING': False,
|
||||
'SQLALCHEMY_DATABASE_URI': Config.SQLALCHEMY_DATABASE_URI,
|
||||
'SECRET_KEY': Config.SECRET_KEY,
|
||||
'LANGUAGES': Config.LANGUAGES
|
||||
}
|
||||
|
||||
def app_context(self):
|
||||
return DummyContext()
|
||||
|
||||
def test_client(self):
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app as fastapi_app
|
||||
return TestClientWrapper(TestClient(fastapi_app))
|
||||
|
||||
def create_app(config_class: Any = Config) -> AppCompatWrapper:
|
||||
return AppCompatWrapper(config_class)
|
||||
Reference in New Issue
Block a user