Messages about socket.io flash drive events in different files

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 raised if it is in the electionAdministration.py file. When I move it to socketservice.py , it fires unexpectedly.

But I mean that I can’t put everything in one file, since it will be very dirty as the application grows.

+5
source share
1 answer

What you need to do is import your add-on module into the main module, but you need to do this after creating the socketio variable, because if you do not encounter 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) 

Also, you need to consider that your main Python script will not be called socketservice , because Python always calls the top level script __main__ . So, if you run the above script as the main script, the second file should import socketio as follows:

 from __main__ import socketio 

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

 try: from __main__ import socketio except ImportError: from socketservice import socketio 
+2
source

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


All Articles