首页 > 解决方案 > sqlalchemy - 将会话用作带有 sqlite 的上下文管理器时出现 DetachedInstanceError

问题描述

我确定某处有重复,但找​​不到。如果你这样做,请将此问题标记为重复。

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

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但是,只要访问 from 的返回值,就会引发以下代码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

标签: pythonsqlitesqlalchemy

解决方案


推荐阅读