Web サービスを介して変更されるオブジェクトの永続ストレージとして ZODB を使用しています。以下は、問題を減らした例です。インクリメント関数は、複数のスレッドから呼び出されるものです。私の問題は、インクリメントが 2 つのスレッドから異なるキーに対して同時に呼び出されると、競合エラーが発生することです。
少なくとも異なるキーが適切な方法で変更されている限り、これを解決できるはずだと思いますか? もしそうなら、私は方法の例を見つけることができませんでした... (zodb のドキュメントは、さまざまなサイトに分散しているようです :/ )
どんなアイデアでも嬉しい...
import time
import transaction
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
from ZODB.POSException import ConflictError
def test_db():
store = FileStorage('zodb_storage.fs')
return DB(store)
db_test = test_db()
# app here is a flask-app
@app.route('/increment/<string:key>')
def increment(key):
'''increment the value of a certain key'''
# open connection
conn = db_test.open()
# get the current value:
root = conn.root()
val = root.get(key,0)
# calculate new value
# in the real application this might take some seconds
time.sleep(0.1)
root[key] = val + 1
try:
transaction.commit()
return '%s = %g' % (key, val)
except ConflictError:
transaction.abort()
return 'ConflictError :-('