Вопрос

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?

Это было полезно?

Решение

@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/

Другие советы

Thats the barebone version of the code you want. I would start testing from there. You will have to figure out what you mean by change, so you can atach the right SqlAlchemy event to the type of change you are doing.

User database after insetion listen event

from sqlalchemy import event   
from app import socketio

def after_insert_listener(mapper, connection, target):
    socketio.emit('namespace response',{'data': data[0]},
                  namespace='/namespace')
    print(target.id_user)

event.listen(User, 'after_insert', after_insert_listener)

SocketIO

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top