我是一名开发简单的多用户游戏(想想扫雷游戏)的新手,使用 Flask 作为 API 后端,使用 AngularJS 作为前端。我按照教程构建了 Angular/Flask 应用程序,并使用 Flask-ReSTLess 编写了一个 RESTful API。
现在我想在数据库中的游戏数据发生更改时将事件推送到所有客户端(因为它是通过 POST 发送到一个 ReSTLess 端点)。我在看使用 SqlAlchemy event.listen API调用 Flask-SocketIO emit function向客户端广播数据。这是完成我想要做的事情的合适方法吗?这种方法有缺点吗?
最佳答案
如果您的所有计算都在同一个过程中完成,@CESCO 的回复效果很好。您也可以使用此语法 ( 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)
如果您有兴趣订阅数据库的所有更新,请继续阅读...
但是,如果您的数据库是从另一个进程更新的,那将不起作用。
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
我写了a little demo app展示如何使用 Redis、ZeroMQ 或 socketIO_client 中的任何一个来将实时更新传达给您的服务器。它可能对其他任何试图处理外部数据库访问的人有所帮助。
此外,您可以考虑订阅 postgres 事件: https://blog.andyet.com/2015/04/06/postgres-pubsub-with-json/
关于python - 使用 Flask-SQLAlchemy 事件 API 广播到 Flask-SocketIO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24002306/