-1

I have a run.py file at the top level of my directory where I initialize flask-socketio. That file looks like this:

# /run.py
#!/usr/bin/env python

import os
from src.config import app_config
from dotenv import load_dotenv, find_dotenv
from flask_socketio import SocketIO
from src.app import create_app

load_dotenv(find_dotenv())

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)
socketio = SocketIO(app, async_mode=None)

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  socketio.run(app, host='0.0.0.0', port=port)

My app.py file sits under src/app.py and looks like this:

def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)
  app.config.from_object(app_config[env_name])

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)

  app.register_blueprint(message_blueprint, url_prefix='/api/v1/message')

  return app

I am trying to import the socketio instance into /src/views/MessageView.py

My MessageView.py file looks like this:

from ..models import db
from __main__ import socketio
from ..shared.Authentication import Auth
from threading import Lock
from flask import Flask, render_template, session, request, \
        copy_current_request_context, g, Blueprint, json, Response
from flask_socketio import SocketIO, emit, join_room, leave_room, \
        close_room, rooms, disconnect

message_api = Blueprint('message_api', __name__)
thread = None
thread_lock = Lock()

def background_thread():
    """Example of how to send server generated events to clients."""
    count = 0
    while True:
        socketio.sleep(10)
        count += 1
        socketio.emit('my_response',
                      {'data': 'Server generated event', 'count': count},
                      namespace='/test')


@message_api.route('/')
def index():
    return render_template('index.html', async_mode=socketio.async_mode)


@socketio.on('my_event', namespace='/test')
def test_message(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']})


@socketio.on('my_broadcast_event', namespace='/test')
def test_broadcast_message(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']},
         broadcast=True)


@socketio.on('join', namespace='/test')
def join(message):
    join_room(message['room'])
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': 'In rooms: ' + ', '.join(rooms()),
          'count': session['receive_count']})


@socketio.on('leave', namespace='/test')
def leave(message):
    leave_room(message['room'])
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': 'In rooms: ' + ', '.join(rooms()),
          'count': session['receive_count']})


@socketio.on('close_room', namespace='/test')
def close(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response', {'data': 'Room ' + message['room'] + ' is closing.',
                         'count': session['receive_count']},
         room=message['room'])
    close_room(message['room'])


@socketio.on('my_room_event', namespace='/test')
def send_room_message(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']},
         room=message['room'])


@socketio.on('disconnect_request', namespace='/test')
def disconnect_request():
    @copy_current_request_context
    def can_disconnect():
        disconnect()

    session['receive_count'] = session.get('receive_count', 0) + 1
    # for this emit we use a callback function
    # when the callback function is invoked we know that the message has been
    # received and it is safe to disconnect
    emit('my_response',
         {'data': 'Disconnected!', 'count': session['receive_count']},
         callback=can_disconnect)


@socketio.on('my_ping', namespace='/test')
def ping_pong():
    emit('my_pong')


@socketio.on('connect', namespace='/test')
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(background_thread)
    emit('my_response', {'data': 'Connected', 'count': 0})


@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected', request.sid)

I have spent the last two days scouring the internet for help on how to fix this. The error i receive is:

ImportError: cannot import name 'socketio'

I have tried relative imports as well as monkey_patching. But each time the error still occurs. Any ideas on how to fix the issue would be greatly appreciated.

P.S. I am adapting the example that Miguel has in his flask-socketio repo located here: link. In his example, everything sits in one file, which would work in a basic app, however, for an app with 50+ API endpoints, that is not an optimal solution.

cp-stack
  • 785
  • 3
  • 17
  • 40

1 Answers1

2

Why do you have the SocketIO object in the top-level run.py module? Since this is a Flask extension, it is better to have it with all your other extensions in src/app.py:

from flask_socketio import SocketIO

socketio = SocketIO()

def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)
  app.config.from_object(app_config[env_name])

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)

  # initialize socketio
  socketio.init_app(app)

  app.register_blueprint(message_blueprint, url_prefix='/api/v1/message')

  return app

Then in run.py you can import this object:

from src.app import create_app, socketio

# ...

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)

# ...

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  socketio.run(app, host='0.0.0.0', port=port)

And in the same way you can import it in your MessageView.py module:

from src.app import socketio

socketio.on('whatever')
def do_something(data):
    pass

I have a complete example application that uses this structure here: https://github.com/miguelgrinberg/Flask-SocketIO-Chat.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • Hey @miguel, thanks for the reply, but that is still not fixing my error. I receive the following error from my `MessageView.py` file. `Traceback (most recent call last): File "run.py", line 7, in from src.app import create_app, socketio File "/Users/xxxxx/Desktop/xxxxx/API/src/app.py", line 26, in from .views.MessageView import message_api as message_blueprint File "/Users/xxxxx/Desktop/xxxxx/API/src/views/MessageView.py", line 2, in from ..app import socketio ImportError: cannot import name 'socketio'` – cp-stack Jun 03 '19 at 23:34
  • I was able to fix this latest error. I was importing the messageview blueprint before initializing socketio `from .views.MessageView import message_api as message_blueprint` My final code looks like this. `# initialize socketio socketio.init_app(app) from .views.MessageView import message_api as message_blueprint app.register_blueprint(message_blueprint, url_prefix='/api/v1/message') return app` – cp-stack Jun 04 '19 at 16:20
  • Yes, as you see in my example application sometimes it is necessary to reorder imports or move them below some code to avoid circular references. Glad you figured it out! – Miguel Grinberg Jun 04 '19 at 18:35