Flask-SQLAlchemy with_for_update() row lock

限于喜欢 提交于 2020-04-10 03:49:11

问题


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.

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

Session 2 didn't read the updated value.

I would really like to know where the problem is.


回答1:


After struggling for one whole day, i found the problem.

user = User.query.with_for_update().filter_by(id=userid).first()

should be

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




回答2:


You just need to state what you want to lock:

user = User.query.with_for_update(of=User).filter_by(id=userid).first()
user.money -= 0.1


来源:https://stackoverflow.com/questions/40700309/flask-sqlalchemy-with-for-update-row-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!