feat(migration): v3.8.0 - erradicacion total de flask, persistencia nativa sqlalchemy 2.0 y compatibilidad pura fastapi

This commit is contained in:
2026-10-19 15:49:50 -03:00
parent ae071d7f72
commit 5ed62d5d30
56 changed files with 3706 additions and 12756 deletions
+134 -10
View File
@@ -1,20 +1,144 @@
"""
Database & Persistence Management for FastAPI (Capa 4)
Integrates SQLAlchemy Engine, SessionLocal and get_db dependency.
Database & Persistence Management for FastAPI (Capa 4 - SQLAlchemy 2.0 Nativo)
Provides engine, SessionLocal, scoped_session, and declarative Base without any Flask dependency.
"""
import os
import contextlib
from typing import Generator, Any
from app import create_app, db as flask_db
from sqlalchemy import (
create_engine, Column, Integer, String, Text, Boolean, DateTime, Date, Time, Float,
ForeignKey, Table, and_, or_, not_, desc, asc, func, Index, UniqueConstraint
)
from sqlalchemy.orm import declarative_base, scoped_session, sessionmaker, relationship, backref
import sqlalchemy as sa
from config.config import Config
# Initialize shared application context
flask_app = create_app()
# 1. Configurar Engine y conexión
db_url = Config.SQLALCHEMY_DATABASE_URI
connect_args = {}
if "sqlite" in db_url:
connect_args["check_same_thread"] = False
engine = create_engine(
db_url,
connect_args=connect_args,
pool_pre_ping=True
)
# 2. Sessionmaker y scoped_session nativo
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = scoped_session(SessionLocal)
# 3. Base declarativa con query_property habilitado
Base = declarative_base()
Base.query = session.query_property()
# 4. Wrapper compatible que emula la API de SQLAlchemy de Flask sin requerir Flask
class SQLAlchemyWrapper:
def __init__(self, target_engine, session_factory, base_class):
self.engine = target_engine
self.session = session_factory
self.Model = base_class
# Schema constructs & Types
self.Column = Column
self.Integer = Integer
self.String = String
self.Text = Text
self.Boolean = Boolean
self.DateTime = DateTime
self.Date = Date
self.Time = Time
self.Float = Float
self.ForeignKey = ForeignKey
self.Index = Index
self.UniqueConstraint = UniqueConstraint
# Relationships
self.relationship = relationship
self.backref = backref
# Operators & functions
self.and_ = and_
self.or_ = or_
self.not_ = not_
self.desc = desc
self.asc = asc
self.func = func
@property
def metadata(self):
return self.Model.metadata
def Table(self, name, *args, **kwargs):
from sqlalchemy import MetaData, Table as SaTable
if len(args) == 0 or not isinstance(args[0], MetaData):
return SaTable(name, self.metadata, *args, **kwargs)
return SaTable(name, *args, **kwargs)
def create_all(self, bind=None):
target = bind or self.engine
try:
import app.models # noqa
except Exception:
pass
self.Model.metadata.create_all(bind=target)
def drop_all(self, bind=None):
target = bind or self.engine
try:
import app.models # noqa
except Exception:
pass
self.Model.metadata.drop_all(bind=target)
def init_app(self, app=None):
"""No-op for legacy compatibility"""
pass
def __getattr__(self, name: str) -> Any:
return getattr(sa, name)
db = SQLAlchemyWrapper(engine, session, Base)
def get_db() -> Generator[Any, None, None]:
"""
FastAPI dependency yielding the SQLAlchemy session within Flask app context
to guarantee all models, ORM queries and services work seamlessly.
FastAPI dependency yielding a clean database session per request.
"""
with flask_app.app_context():
yield flask_db.session
db_session = SessionLocal()
try:
yield db_session
finally:
db_session.close()
# Context manager dummy para compatibilidad transitoria
class DummyAppContext:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def push(self):
pass
def pop(self):
pass
class DummyApp:
def __init__(self):
self.config = {
'TESTING': False,
'SQLALCHEMY_DATABASE_URI': Config.SQLALCHEMY_DATABASE_URI,
'SECRET_KEY': Config.SECRET_KEY,
'LANGUAGES': Config.LANGUAGES
}
def app_context(self):
return DummyAppContext()
_dummy_app_instance = DummyApp()
def get_flask_app():
return flask_app
"""
Legacy helper: returns a harmless dummy context object to prevent breakages
during incremental removal of with flask_app.app_context().
"""
return _dummy_app_instance