我目前正在撰寫一個 API,用戶可以在其中將錢從他們的帳戶轉移到手機,但我面臨一個問題,即用戶可以同時多次呼叫 API 并要求轉移資金。通常呼叫后他的賬戶余額不會正確,所以我搜索了很多,發現我可以使用原子事務并鎖定資料庫。現在,如果用戶使用 API 兩次,其中一個運行正常,但另一個django.db.utils.OperationalError: database is locked出現錯誤。知道如何正確處理它們嗎?(我可以使用一段時間并等到資料庫解鎖,但我寧愿不這樣做)
模型.py
@transaction.atomic()
def withdraw(self, amount, phone, username):
property = transferLog.objects.filter(username=username).order_by('-time').select_for_update()[0]
if property.property >= int(amount):
self.username = username
self.property = property.property - int(amount)
self._from = username
self._to = phone
self.amount = int(amount)
self.time = str(datetime.datetime.now())
self.save()
return {'result': 'success', 'message': 'transfer complete', 'remaining': self.property}
else:
return {'result': 'error', 'message': 'not enough money'}
uj5u.com熱心網友回復:
我猜你正在使用 SQLite 資料庫。它不允許并發寫入,即在給定時間有多個寫入操作。
你必須選擇:
- 要么切換到不同的資料庫
- 或者
timeout在設定中增加資料庫選項
例子:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
'OPTIONS': {
'timeout': 60, # 1 minute
}
}
}
這不是一個可擴展的解決方案。假設您有許多行程在等待寫入訪問,OperationalError如果有任何行程在 60 秒后仍在等待,您可能仍然會得到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352956.html
標籤:Python 姜戈 sqlite django-models
