python - 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
解决方案
推荐阅读
- java - 使用 XFCE 的 JavaFx 启动缓慢
- flutter - 为什么颤振总是加载最新的库
- android - 计算两个日期之间的分钟数
- azure - 如何使用 rest api 触发 azure 构建队列
- android - 用树莓派连接手机音频
- typescript - 此条件将始终返回 'false',因为类型 'T[keyof T]' 和 'string' 没有重叠
- jquery - Chrome 没有在 popstate 上获得会话存储
- cron - 如何在骆驼运行时动态设置石英cron表达式?
- spring - Spring Boot 和 PostgreSQL - 没有打印数据
- python - 如何在没有 Pandas 的情况下获取指定行的索引?