Using Flask-SQLAlchemy Event API to broadcast to Flask-SocketIO?

angularjs, flask, flask-sqlalchemy, python, socket.io

Solution

@CESCO's reply works great if all of your computation is being done in the same process. You could also use this syntax (see full source code here):

@sa.models_committed.connect_via(app)
def on_models_committed(sender, changes):
    for obj, change in changes:
        print 'SQLALCHEMY - %s %s' % (change, obj)

Read on if you're interested in subscribing to all updates to a database ...

That won't work if your database is being updated from another process, however.

models_committed only works in the same process where the commit comes from (it's not a DB-level notification, it's sqlalchemy after committing to the DB)

https://github.com/mitsuhiko/flask-sqlalchemy/issues/369#issuecomment-170272020

I wrote a little demo app showing how to use any of Redis, ZeroMQ or socketIO_client to communicate real-time updates to your server. It might be helpful for anyone else trying to deal with outside database access.

Also, you could look into subscribing to postgres events: https://blog.andyet.com/2015/04/06/postgres-pubsub-with-json/

Problem

I'm a novice developing a simple multi-user game (think Minesweeper) using Flask for the API backend and AngularJS for the frontend. I've followed tutorials to structure the Angular/Flask app and I've coded up a RESTful API using Flask-Restless. Now I'd like to push events to all the clients when game data is changed in the database (as it is by a POST to one the Restless endpoints). I was looking at using the SqlAlchemy event.listen API to call the Flask-SocketIO emit function to broadcast the data to clients. Is this an appropriate method to accomplish what I'm trying to do? Are there drawbacks to this approach?

Original source