Flask socket.io message events in different files

依然范特西╮ 提交于 2020-08-02 12:12:34

问题


socketservice.py:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from backend.database import db

app = Flask(__name__)
socketio = SocketIO(app, engineio_logger=True)

@socketio.on('connect')
def handle_connection():
    from backend.electionAdministration import syncElections
    syncElections()

if __name__ == '__main__':
    socketio.run(app)

electionAdministration.py:

from flask_socketio import SocketIO, emit
from bson.json_util import dumps
from backend.socketservice import socketio
from backend.database import db

def syncElections():
    elections = db.elections.find()
    emit('syncElections',dumps(res) , broadcast=True)

@socketio.on('createElection')
def createElection(data):
    db.elections.insert({'title': data["title"]})
    syncElections()

The problem is, that the createElection event is never being called, when it is within the file electionAdministration.py. When I move it into socketservice.py, it suddenly works.

But I mean, I cannot put everything into one file, as it will get very messy as the application grows.


回答1:


What you need to do is import your secondary module in the main module, but you need to do it after the socketio variable is created, because if not you will run into circular dependency errors.

Example:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from backend.database import db

app = Flask(__name__)
socketio = SocketIO(app, engineio_logger=True)

@socketio.on('connect')
def handle_connection():
    from backend.electionAdministration import syncElections
    syncElections()

import electionAdministration  # <--- import your events here!

if __name__ == '__main__':
    socketio.run(app)

In addition, you need to consider that your main Python script is not going to be called socketservice, because Python always names the top-level script __main__. So, if you start the above script as your main script, the second file should import socketio as follows:

from __main__ import socketio

This is a small annoyance with Python, which is made worse when you want to have a script that you sometimes run as a main script, but other times you also want it to be imported by another script. To make the import work in such case, I use the following trick:

try:
    from __main__ import socketio
except ImportError:
    from socketservice import socketio


来源:https://stackoverflow.com/questions/46622408/flask-socket-io-message-events-in-different-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!