user5201343
user5201343

Reputation:

How can I emit from a seperate file with socketio? (flask)

How do I allow a separate file (in this case, classes.py) to emit socketio messages?

classes.py has know knowledge of the socketio variable, and even after trying to import it directly, it does not work.

Please help me solve my issue!

Here is my code;

app.py
from flask import Flask, render_template, redirect, url_for, request, session, send_from_directory, jsonify
from flask_socketio import SocketIO
from classes import *

app = Flask(__name__)
socketio = SocketIO(app, message_queue='redis://localhost:6379')

if __name__ == "__main__":
    app.debug = True
    socketio.run(app, port=5000, debug=True, use_reloader=True)
classes.py
from flask import Flask, request, session, redirect, url_for, jsonify
import requests, json, random, sqlite3
from flask_socketio import SocketIO

class notify:
    def __init__(self, message=None):
        socketio.emit('notification', {'message': message})

My current fix

Upvotes: 1

Views: 2645

Answers (1)

thara
thara

Reputation: 133

It seems to have a circular reference. You should divide app variable from the entry point.

app.py

from flask import Flask, render_template, redirect, url_for, request, session, send_from_directory, jsonify
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app, message_queue='redis://localhost:6379')

classes.py

from app import socketio

class notify:
    def __init__(self, message=None):
        socketio.emit('notification', {'message': message})

main.py

from app import app, socketio
from classes import *

if __name__ == "__main__":
    app.debug = True
    socketio.run(app, port=5000, debug=True, use_reloader=True)

Upvotes: 5

Related Questions