我正在使用 RESTful 框架(带有 Flask-SQLAlchemy 的 Flask-Restless 0.17.0)作为后端。而 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-column 并为其创建一个标头:
@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 的可能性。
任何帮助表示赞赏。