sqlalchemy-将会话用作带sqlite的contextmanager时出现DetachedInstanceError

时间:2019-05-06 12:44:44

标签: python sqlite sqlalchemy

我确定某个地方有重复项,但找不到。如果您这样做,请将此问题标记为重复。

考虑一个根本没有关系的非常基本的模型:

class Match(Base):
    __tablename__ = 'matches'

    match_date = Column(DateTime, primary_key=True)
    stadium = Column(String)
    opponent = Column(String)
    is_date_final = Column(Boolean)

DAL类:

class DB:
    def __init__(self, log_level):
        self.engine = create_engine('sqlite:///db/db.sqlite')
        self.connection = self.engine.connect()
        self.Session = sessionmaker(bind=self.engine)
        Base.metadata.create_all(self.engine)

我对这段代码为什么起作用感到困惑:

def get_next_matches(self):
    session = self.Session()
    next_matches = session.query(Match).all()
    session.close()

    return next_matches

但是,一旦访问DetachedInstanceError的返回值,以下代码将引发get_next_matches

...

@contextmanager
def create_session_scope(session_maker):
    """Provides a transactional scope around a series of operations."""
    session = session_maker()
    try:
        yield session
        session.commit()
    except SQLAlchemyError:
        session.rollback()
        raise
    finally:
        session.close()
...

def get_next_matches(self):
    with create_session_scope(self.Session) as session:
        next_matches = session.query(Match).all()

    return next_matches

0 个答案:

没有答案