[英]Where to session.commit() for a SELECT query - SQLALchemy, Flask
My application does not update the database - all queries are SELECT
statements.我的应用程序不更新数据库 - 所有查询都是
SELECT
语句。 I'm struggling how best to handle direct changes to the database (ie opening MySQLWorkbench and changing data there).我正在努力如何最好地处理对数据库的直接更改(即打开 MySQLWorkbench 并在那里更改数据)。 Without
session.commit()
, my Flask application is returning stale data.如果没有
session.commit()
,我的 Flask 应用程序将返回陈旧数据。
My solution right now is to have a session.commit()
as the first line of each Flask endpoint, but I feel this is the incorrect way of handling this.我现在的解决方案是将
session.commit()
作为每个 Flask 端点的第一行,但我觉得这是处理此问题的不正确方式。
Session creation at start of app:在应用程序启动时创建会话:
engine = db.create_engine('mysql+pymysql://...')
connection = engine.connect()
metadata = db.MetaData()
Base = declarative_base()
Session = sessionmaker(autoflush=True)
Session.configure(bind=engine)
session = Session()
session.expire_all()
to mark all session data as expired. session.expire_all()
将所有会话数据标记为过期。 Then when you are trying to access something, it will be fetched from the database.然后当您尝试访问某些内容时,它将从数据库中获取。
session.expire(object)
does the same but for objects only session.expire(object)
做同样的事,但只针对对象
db.session.refresh(some_object)
expires and reloads all object data db.session.refresh(some_object)
过期并重新加载所有对象数据
Nice article about that can be found here: https://www.michaelcho.me/article/sqlalchemy-commit-flush-expire-refresh-merge-whats-the-difference可以在这里找到关于这方面的好文章: https : //www.michaelcho.me/article/sqlalchemy-commit-flush-expire-refresh-merge-whats-the-difference
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.