4

I am trying to integrate Flask-SocketIO with my Flask application.

For some reason I am getting an import error that is triggered by the from .. import socketio that I have in my events.py and I am not sure why.

I would greatly appreciate any help provided.

app.py

from factory import create_app
app = create_app()

factory.py

from flask import Flask
from flask.ext.socketio import SocketIO
from flask.ext.login import LoginManager
import os
from celery import Celery

lm = LoginManager()
socketio = SocketIO()
lm.login_view = 'main.login'
lm.session_protection = 'strong'


def create_app():
    app = Flask(__name__)
    app.config.from_object(os.environ.get('APP_CONFIG'))  # export APP_CONFIG=settings.Development
    lm.init_app(app)

    from project.main import main as main_blueprint

    app.register_blueprint(main_blueprint)
    socketio.init_app(app)

    return app

main/____init____.py

from flask import Blueprint

main = Blueprint('main', __name__)
import views, events

main/events.py

# from __future__ import absolute_import
from uuid import uuid4
from flask import current_app, session, request
from flask.ext.socketio import emit, disconnect
from .. import socketio

@socketio.on('status', namespace='/events')
def events_message(message):
    print 'socketio.on: status'
    emit('status', {'status': message['status']})


@socketio.on('disconnect request', namespace='/events')
def disconnect_request():
    print 'socketio.on: disconnect request'
    emit('status', {'status': 'Disconnected!'})
    disconnect()


@socketio.on('connect', namespace='/events')
def events_connect():
    print 'socketio.on: connect'
    websocket_id = str(uuid4())
    session['websocket_id'] = websocket_id
    current_app.clients[websocket_id] = request.namespace
    emit('websocket_id', {'websocket_id': websocket_id})
1
  • How to use it in production ? I mean eventlet server. Commented Apr 10, 2020 at 21:54

1 Answer 1

4

Rename main/____init____.py to main/__init__.py and you can do:

from . import socketio

if socketio is defined in __init__.py like you said. However, it looks like it's defined in factory.py, in which case you'd do:

from ..factory import socketio
Sign up to request clarification or add additional context in comments.

1 Comment

Ok I must've typed one to many _ when I was entering the name of my init file on SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.