Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

418
Visualizações
Flask socket IO emit from another module

I have almost read every piece of article available on the internet but nothing seems to work for my case. I have installed flask-socketio and everything works fine until I emit the messages from a module other than app.py.

I have tried several ways to accomplish this and I have also read in the doc about it by using Redis but it also did not work for me. Here are the code snippets that I have.

app.py

from flask import Flask
from flask import request
from flask_socketio import send, SocketIO, emit, join_room

app = Flask(__name__)

# This is to stop force sorting in response, by default jsonify sorts the response keys alphabetically
app.config["JSON_SORT_KEYS"] = False

socketio = SocketIO(app, cors_allowed_origins="*")

@socketio.on('join')
def client_join_room(data):
    print(type(data))
    room = data['room']
    join_room(room)
    send('you have entered the room.', room=room)


@app.route('/msg')
def send_message():
    socketio.emit("message", "Server message", room='my_room')
    return "I got you."



if __name__ == '__main__':
    socketio.run(host="0.0.0.0", port=5001, debug=True, app=app)

my_module.py

def some_method():
    import app
    app.socketio.emit("message", "Some information about process", room='my_room', broadcast=True)

Note that I have imported app inside the method because app.py also imports my_module.py

  1. I am able to join room.

  2. When I call localhost:5001/msg it does emit to 'my_room'.

  3. The emit does not work inside my_module.py and I have no idea why.

I am consoling the messages that I get from the server at the front-end so I know for sure which messages are received and which are not.

Also, the some_method() here is called by an API request from app.py. Just in case if that is relevant.

I have made logger=True and then I get this message printed on the terminal for each emit call. Even with the one inside some_method()

emitting event "message" to my_room [/]

Does that mean message is actually sent? If yes, then why am I not getting it in the jquery at front-end.

This is what I am doing in html page

$(document).ready(function () {
        // start up the SocketIO connection to the server
        var socket = io.connect('http://localhost:5001/');
        // this is a callback that triggers when the "message" event is emitted by the server.

        socket.on('message', function(msg){
            console.log(msg)
        });

            socket.emit('join', {room: 'my_room'});
    });
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Please try and install Redis and eventlet for asynchronous calls and to send messages from other modules. As described in the documentation then you can change your line in app.py to

socketio = SocketIO(app, cors_allowed_origins="*", message_queue='redis://', async_mode='eventlet')
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda