我使用RESTful框架(Flask Restless 0.17.0 with Flask SQLAlchemy)作为后端。和AngularJS作为前端。
我知道可以使用单个表的版本列(或数据的时间戳或校验和)来处理并发性。
我现在处理它的方式是这样的:
所有SQLAlchemy模型都继承自CommonColumns:
class CommonColumns(db.Model):
__abstract__ = True
id = db.Column(db.Integer, primary_key=True)
aangemaakt = db.Column(db.DateTime)
gewijzigd = db.Column(db.DateTime)
etag = db.Column(db.String(40))
def commoncolumns_on_before_insert(mapper, connection, target):
""" Set time created and generate ETag on before_insert event. """
# Set time created.
target.aangemaakt = datetime.now()
# Generate ETag based on SHA1-hash of time created.
target.etag = hashlib.sha1(str(target.aangemaakt)).hexdigest()
def commoncolumns_on_before_update(mapper, connection, target):
""" Set time updated and generate ETag on before_update event. """
# Set time updated.
target.gewijzigd = datetime.now()
# Generate ETag based on SHA1-hash of time updated.
target.etag = hashlib.sha1(str(target.gewijzigd)).hexdigest()
event.listen(CommonColumns, 'before_insert', commoncolumns_on_before_insert, propagate = True)
event.listen(CommonColumns, 'before_update', commoncolumns_on_before_update, propagate = True)
在每个请求之后,一些代码都会查找etag列,并为其创建一个标题:
@app.after_request
def add_etag_header(response):
""" Add etag-header contained in 'etag'-field inside returned JSON-object.
If no JSON returned, it wil silently ignore the exception and return the
response it would have returned anyway.
"""
try:
# Parse JSON.
jsonObject = json.loads(response.get_data())
# Get etag field (if one)
etag = jsonObject.get('etag', None)
if etag != None:
# Return ETag as a header (for client, e.g. Restangular).
response.headers['ETag'] = etag
except Exception:
# Some unexpected exception occurred. Ignore for now.
pass
return response
然后,对于每个API资源,我使用一个预处理器来调用这个函数:
def abort_on_etag_collision(model, instance_id):
""" Abort PUT/DELETE-operation for model (with ID=instance_id) when there is a 'mid-air-collision'
(when client-side and server-side ETags do not match). """
# Store client-side ETag for comparison.
hdr_ifmatch_etag = request.headers.get('If-Match', None)
# Get server-side ETag from model for comparison.
current_etag = db.session.query(model).get(instance_id).etag
if current_etag == hdr_ifmatch_etag:
# Current ETag matches client-specified ETag, so let request through
pass
else:
# Current ETag is different from client-specified ETag, so return a 412 Precondition Failed!
# Also called a 'mid-air-collision'...
raise ProcessingException(description='Precondition Failed', code=412)
我想"abort_on_etag_collision"函数也容易受到竞争条件的影响?
但是,第二,如果您有多个相关的表,该怎么办。您可以通过父资源访问这些表,也可以通过子资源访问。我很难弄清楚什么是最好或最灵活的处理方式。
我想使用SQLALchemy的版本控制功能:http://docs.sqlalchemy.org/en/rel_1_0/orm/versioning.html
但是,我必须能够修改SQL,以便自己包含对版本的WHERE检查,因为SQLAlchemy不会自动执行此操作,而且我认为使用Flask Restless也不可能执行此操作。
感谢您的帮助。
我在这里找到了问题的答案:https://stackoverflow.com/a/14690307/694400
摘要:我应该只使用校验和(而不是使用时间戳)。