SQLAlchemy Session.Refresh不刷新对象 [英] Sqlalchemy session.refresh does not refresh object

查看:735
本文介绍了SQLAlchemy Session.Refresh不刷新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下映射(直接来自SA示例):

I have the following mapping (straight from SA examples):

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

我正在使用MySql数据库,并且该表具有innoDB引擎.

I'm working with a MySql DB and the table has an innoDB engine.

我的表中有一条记录: 1 |'user1'|'user1 test'|'password'

I have a single record in my table: 1|'user1'|'user1 test'|'password'

我用以下代码打开了一个会话:

I've opened a session with the following code:

from sqlalchemy.orm.session import sessionmaker
from sqlalchemy.engine import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

db_engine = create_engine('mysql://...@localhost/test_db?charset=utf8',echo=False,pool_recycle=1800)
session_factory = sessionmaker(bind=db_engine,autocommit=False,autoflush=False)
session_maker = scoped_session(session_factory)
session = session_maker()

user_1 = session.query(User).filter(User.id==1).one()
user_1.name # This prints: u'user1'

现在,当我将数据库中的记录名称更改为'user1_change'并提交它,然后像这样刷新对象时:

Now, when I change the record's name in the DB to 'user1_change' and commit it and then refresh the object like this:

session.refresh(user_1)
user_1.name # This still prints: u'user1' and not u'user1_change'

它仍然打印:u'user1',而不是u'user1_change'.

It still prints: u'user1' and not u'user1_change'.

我在这里想念什么(或设置错误)?

What am I missing (or setting up wrong) here?

谢谢!

推荐答案

来自

请注意,高度隔离的事务将返回与先前在同一事务中读取的值相同的值,而不管该事务之外的数据库状态如何更改

Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction

SQLAlchemy使用事务性工作单元模型,其中假定每个事务在内部都是一致的.会话是事务顶部的接口.由于假定事务在内部是一致的,所以SQLAlchemy仅(很好,为了解释方便...)将从数据库中检索给定的数据,并且每个事务一次更新关联对象的状态.由于您已经在同一会话事务中查询了对象,因此SQLAlchemy不会在该事务范围内再次从数据库中更新该对象中的数据.如果要轮询数据库,则每次都需要使用新的事务进行处理.

SQLAlchemy uses a transactional unit of work model, wherein each transaction is assumed to be internally consistent. A session is an interface on top of a transaction. Since a transaction is assumed to be internally consistent, SQLAlchemy will only (well, not quite, but for ease of explanation...) retrieve a given piece of data from the database and update the state of the associated objects once per transaction. Since you already queried for the object in the same session transaction, SQLAlchemy will not update the data in that object from the database again within that transaction scope. If you want to poll the database, you'll need to do it with a fresh transaction each time.

这篇关于SQLAlchemy Session.Refresh不刷新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆