要从顶级文件导入flask-socketio实例吗?

时间:2019-06-03 04:50:31

标签: flask flask-socketio

我在初始化flask-socketio的目录的顶层有一个run.py文件。该文件如下所示:

# /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)

我的app.py文件位于src/app.py下,看起来像这样:

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

我正在尝试将socketio实例导入/src/views/MessageView.py

我的MessageView.py文件如下:

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)

最近两天,我一直在互联网上搜寻有关如何解决此问题的帮助。我收到的错误是:

ImportError: cannot import name 'socketio'

我尝试了相对导入以及monkey_patching。但是每次错误仍然发生。任何有关解决此问题的想法将不胜感激。

P.S。我正在改编Miguel在他的flask-socketio存储区中位于link的示例。在他的示例中,所有内容都放在一个文件中,该文件可以在基本应用程序中运行,但是,对于具有50个以上API端点的应用程序,这不是最佳解决方案。

1 个答案:

答案 0 :(得分:1)

为什么在顶层run.py模块中有SocketIO对象?由于这是Flask扩展程序,因此最好与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

然后在run.py中,您可以导入该对象:

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)

并且可以用相同的方式将其导入到MessageView.py模块中:

from src.app import socketio

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

我有一个使用以下结构的完整示例应用程序:https://github.com/miguelgrinberg/Flask-SocketIO-Chat