简体   繁体   中英

Flask and SqlAlchemy session

I've been building a flask app and using flask-sqlalchemy and flask-migrate. Lately I decided to replace the extension with plain sqlalchemy and alembic and I started to think what's the best place to store the db session object (sqla).

Right now I have the following:

Base = declarative_base()


def init_db_session(app, expire_on_commit=True):
    """
    Initialize the database
    """
    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
    db_session = scoped_session(
        sessionmaker(autocommit=False, autoflush=False, expire_on_commit=expire_on_commit, bind=engine)
    )

    Base.query = db_session.query_property()

    return db_session

def init_app(app):
    """
    Flask app initialization and bootstrap
    """
    init_logging(app)
    app.celery = init_celery(app)
    app.db_session = init_db_session(app)

but given some docs and examples online I'm wondering if using flask global g is any better

They both belong to the same context, I read about that in the docs and in the code but still can't get my head around the practical differences and the potential drawbacks of having it in the current_app compared to g

The flask documentation has a recommendation to declare the session in the module scope. This is also how I use it in my own code.

Base = declarative_base()
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
db_session = scoped_session(
    sessionmaker(
        autocommit=False,
        autoflush=False,
        expire_on_commit=expire_on_commit,
        bind=engine
    )
)

Base.query = db_session.query_property()


def init_db():
""" not much to do here if migrations are handled else where. """
    pass


def init_app(app):
    """
    Flask app initialization and bootstrap
    """
    init_logging(app)
    app.celery = init_celery(app)
    app.db_session = init_db_session(app)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM