Question: Flask socket.io message events in different files

Question

Flask socket.io message events in different files

Answers 1
Added at 2017-10-07 18:10
Tags
Question

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.

Answers to

Flask socket.io message events in different files

nr: #1 dodano: 2017-10-09 03:10

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
Source Show
◀ Wstecz