Using the Flask-SQLAlchemy event API to translate to Flask-SocketIO?

I am starting to develop a simple multiplayer game (think Minesweeper) using Flask for the API and AngularJS for the interface. I followed tutorials to structure the Angular / Flask application, and I encoded a RESTful API using Flask-Restless.

Now I would like to click events for all clients when the game data is changed in the database (same as POST for one Restless endpoint). I was looking for using the SqlAlchemy event.listen API to call the Flask-SocketIO emission function to broadcast data to clients. Is this a suitable method to accomplish what I'm trying to do? Are there any flaws in this approach?

+6
source share
2 answers
Answer to

@CESCO works great if all of your calculations are done in the same process. You can 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 if you are interested in subscribing to all database updates ...




This will not work if your database is updated from another process.

models_committed only works in the same process in which the commit occurs (this is not a notification at the DB level, it is sqlalchemy after the transaction with the database)

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

I wrote a small demo application that shows how to use any of Redis, ZeroMQ or socketIO_client to send real-time updates to your server. This can be useful for anyone trying to cope with external access to the database.

In addition, you can see the subscription to postgres events: https://blog.andyet.com/2015/04/06/postgres-pubsub-with-json/

+2
source

This is a simple version of the code you want. I would start testing from there. You will need to figure out what you mean by the change so that you can give the correct SqlAlchemy event the type of change you are making.

User database after insert 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

+1
source

Source: https://habr.com/ru/post/970200/


All Articles