如何处理REST资源的乐观并发?

时间:2016-05-11 08:14:46

标签: python rest sqlalchemy optimistic-locking flask-restless

我使用RESTful框架(Flask-Restless 0.17.0与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-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没有自动执行此操作,并且我没有看到使用它的可能性烧瓶-不宁。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我在这里找到了我的问题的答案: https://stackoverflow.com/a/14690307/694400

要点: 我应该为此使用校验和(而不是使用时间戳)。