SQLAlchemy: Creating vs. Reusing a Session

后端 未结 2 1888
臣服心动
臣服心动 2020-12-22 15:08

Just a quick question: SQLAlchemy talks about calling sessionmaker() once but calling the resulting Session() class each time you need to talk to y

2条回答
  •  悲&欢浪女
    2020-12-22 15:41

    In addition to the excellent zzzeek's answer, here's a simple recipe to quickly create throwaway, self-enclosed sessions:

    from contextlib import contextmanager
    
    from sqlalchemy import create_engine
    from sqlalchemy.orm import scoped_session, sessionmaker
    
    @contextmanager
    def db_session(db_url):
        """ Creates a context with an open SQLAlchemy session.
        """
        engine = create_engine(db_url, convert_unicode=True)
        connection = engine.connect()
        db_session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine))
        yield db_session
        db_session.close()
        connection.close()
    

    Usage:

    from mymodels import Foo
    
    with db_session("sqlite://") as db:
        foos = db.query(Foo).all()
    

提交回复
热议问题