0

I'm using a RESTful framework (Flask-Restless 0.17.0 with Flask-SQLAlchemy) as a backend. And AngularJS as a frontend.

I know one can handle concurrency using for example a version column (or a timestamp or a checksum of the data) for a single table.

The way I am now handling it is like this:

All SQLAlchemy-models are inheriting from 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)

After each request some code looks for the etag-column and creates a header for it:

@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    

Then for each API resource I use a preprocessor which calls this function:

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)

I guess the 'abort_on_etag_collision' function is vulnerable to a race condition also?

But, secondly, what if you have multiple related tables. And you can access these tables via a parent resource, but also via child resources. I have a hard time figuring out what is the best or most flexible way to deal with this.

I would like to use the versioning feature of SQLALchemy: http://docs.sqlalchemy.org/en/rel_1_0/orm/versioning.html

But then I have to be able to modify the SQL to include a WHERE-check for the version(s) myself as SQLAlchemy doesn't do this automatically and I don't see a possibility for this using Flask-Restless.

Any help is appreciated.

Wieger
  • 663
  • 1
  • 9
  • 24

1 Answers1

0

I found the answer to my question here: https://stackoverflow.com/a/14690307/694400

Summary: I should just use a checksum for this (instead of using a timestamp).

Community
  • 1
  • 1
Wieger
  • 663
  • 1
  • 9
  • 24
  • 1
    Hi there - when you realize you've found the answer on another question in Stack Overflow, it's often best to close your original question as a duplicate of that one. This way, duplicate questions serve as signposts to a central Q/A, rather than fragmenting the answers across questions. – Serlite May 12 '16 at 22:27
  • @Serlite Seems logical. I'll try that! – Wieger May 13 '16 at 04:28