Flask-SQLAlchemy with_for_update()行锁 [英] Flask-SQLAlchemy with_for_update() row lock
问题描述
我有一个名为用户"的模型,而用户"有钱".
在这种情况下,多个会话可以读取模型用户"并同时更新金钱".
I have a model called 'User', and 'User' has 'Money'.
There a scenario that multiple session can read the model 'User' and update 'money' at the same time.
会话1成功更新后,会话2应该读取'money'值.
我尝试在更新时锁定用户"行.
这是我的代码.
Session 2 should read the 'money' value after session 1 updated successfully.
I tried to lock the 'User' row when updating.
Here's my code.
user = User.query.with_for_update().filter_by(id=userid).first()
print('000000')
before_money = user.money
print('111111')
time.sleep(1)
user.money -= 0.1
print('User:' + str(user.id) + '***' + str(before_money) + '-' + str(0.1) + ' = ' + str(user.money))
time.sleep(1)
db.session.commit()
print('22222')
我打开了两个会话以同时运行此代码,输出
I opened two session to run this code at the same time, the output
000000
111111
User:1***125.3-0.1 = 125.2
000000
111111
22222
User:1***125.3-0.1 = 125.2
22222
会话2未读取更新的值.
Session 2 didn't read the updated value.
我真的很想知道问题出在哪里.
I would really like to know where the problem is.
推荐答案
奋斗了整整一天之后,我发现了问题所在.
After struggling for one whole day, i found the problem.
user = User.query.with_for_update().filter_by(id=userid).first()
应该是
result = db.session.query(User.money).with_for_update().filter_by(id=userid).first()
money = result[0]
user.money = money - 0.1
是的,很简单,但很烦人
Yes, so simple but annoying
这篇关于Flask-SQLAlchemy with_for_update()行锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!