gpt4 book ai didi

python - SQLAlchemy:session.close() 或 session.commit()

转载 作者:行者123 更新时间:2023-12-03 17:40:07 24 4
gpt4 key购买 nike

我是 SQLAlchemy 的新手。而现在我需要查询一些数据,如下

def get_xx():
sess = Session()
return sess.query(xx).filter(
xx.id == 3, xx.status == 1
).first()

隔离级别为 repeatable read并且自动提交已关闭;因此,即使值已更新,我也总是得到相同的结果。

现在,问题出现了,sess.close() 和 sess.commit(),我应该使用哪种方法?

我尝试使用的最终解决方案如下,但是我不确定它是否足够好(提交后关闭)?
@contextmanager
def auto_session():
sess = Session()
try:
yield sess
sess.commit()
except: # swallow any exception
sess.rollback()
finally:
sess.close()

并且源代码改变了
def get_xx():
with auto_session() as sess:
return sess.query(xx).filter(
xx.id == 3, xx.status == 1
).first()

最佳答案

您的 session 提交和关闭完全正确。在你的源代码中你可以试试这个..

from operator import and_
def get_xx():
with auto_session() as sess:
return sess.query(xx).filter(and_(
xx.id == 3, xx.status == 1
)).first()

关于python - SQLAlchemy:session.close() 或 session.commit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com