SQLAlchemy如何跟踪数据库更改?

时间:2015-11-18 17:19:58

标签: python orm flask sqlalchemy flask-sqlalchemy

我想知道SQLAlchemy如何跟踪SQLAlchemy之外的更改(例如手动更改)?

到目前为止,我曾经在每个可以在SQLAlchemy之外更改的值之前放置db.session.commit()。这是一种不好的做法吗?如果是的话,是否有更好的方法来确保我拥有最新价值?我实际上在下面创建了一个小脚本来检查这一点,显然,SQLAlchemy可以检测到外部更改而不会每次调用db.session.commit()

谢谢,

P.S:我真的想了解SQLAlchemy工作背后的所有魔法是如何发生的。有没有人指向一些解释SQLAlchemy幕后工作的文档?

import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# Use SQLlite so this example can be run anywhere.
# On Mysql, the same behaviour is observed
basedir = os.path.abspath(os.path.dirname(__file__))
db_path = os.path.join(basedir, "app.db")
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + db_path
db = SQLAlchemy(app)


# A small class to use in the test
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))


# Create all the tables and a fake data
db.create_all()
user = User(name="old name")
db.session.add(user)
db.session.commit()


@app.route('/')
def index():
    """The scenario: the first request returns "old name" as expected.
    Then, I modify the name of User:1 to "new name" directly on the database.
    On the next request, "new name" will be returned.
    My question is: how SQLAlchemy knows that the value has been changed?
    """

    # Before, I always use db.session.commit() 
    # to make sure that the latest value is fetched.
    # Without db.session.commit(), 
    # SQLAlchemy still can track change made on User.name
    # print "refresh db"
    # db.session.commit()

    u = User.query.filter_by(id=1).first()
    return u.name


app.run(debug=True)

1 个答案:

答案 0 :(得分:4)

会话的“缓存”是其identity_map(session.identity_map.dict)中的一个字典,它仅在“单个业务事务”的时间内缓存对象,如此处https://stackoverflow.com/a/5869795所述。

对于不同的服务器请求,您有不同的identity_map。它不是共享对象。

在您的方案中,您分别请求服务器2次。第二次,identity_map是一个新的(您可以通过打印其指针轻松检查它),并且在缓存中没有任何内容。因此,会话将请求数据库并获得更新的答案。它没有像你想象的那样“跟踪变化”。

因此,对于您的问题,如果您未在相同的服务器请求中对同一对象进行查询,则不需要在查询之前执行session.commit()

希望它有所帮助。