我正在尝试将Flask-SocketIO与我的Flask应用程序集成。
由于某种原因,我收到了由。触发的导入错误 来自应用导入套接字的 ; 我在admin.py中有,我不知道为什么。
我非常感谢您提供的任何帮助。
admin_online / admin.py
from flask_socketio import send, emit
from flask_socketio import join_room, leave_room
from app import sockets;
#from .. import sockets//error
# from ..app import socket //also an error
from flask import Blueprint
admin_online=Blueprint('admin_online', __name__)
@sockets.on('add-message', namespace='/')
def send_disconnect(message):
print ',messae';
emit('message', message)
@sockets.on('disconnect', namespace='/')
def test_disconnect():
realoutput = "No"
print 'dscone';
@sockets.on('join', namespace='/')
def on_join(data):
username = data['username']
room = data['room']
print 'coonectg'+username;
join_room(room)
emit('message', username)
@sockets.on('leave', namespace='/')
def on_leave(data):
username = data['username']
room = data['room']
leave_room(room)
print 'leaving';
emit('message', username)
app.py
from flask import Flask
from mongo import init_mongo
from mail import init_flask_mail
from celery import Celery
from sockets import init_sockets
from admin_online import admin
def init_app():
return Flask(__name__)
app = init_app()
# Celery configuration
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
app.config['CELERY_REDIRECT_STDOUTS_LEVEL'] = 'INFO'
def make_celery():
celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
with app.app_context():
init_flask_mail()
init_mongo()
sockets = init_sockets()
##imported here TOO but not worked from admin_online import admin
app.register_blueprint(admin.admin_online)
if __name__ == '__main__':
sockets.run(app, port=5000, debug=True)
socket.py
from flask import current_app as app
from flask_socketio import SocketIO
socketio = None
def init_sockets():
return SocketIO(app)
app结构
admin_online / admin.py
app.py
sockets.py
错误
Traceback (most recent call last):
File "app.py", line 19, in <module>
from admin_online import admin
File "E:\Iccacerate\ICaccerate-Backend\icarcerate-backend\admin_online\admin.py", line 3, in <module>
from app import sockets;
File "E:\Ii\app.py", line 19, in <module>
from admin_online import admin
ImportError: cannot import name admin
答案 0 :(得分:0)
您有循环导入。问题如下:
app.py
尝试从admin
导入admin_online.py
(请注意,这位于app.py
中定义sockets
的位置之上)admin_online/admin.py
尝试从sockets
导入app.py
,但尚未存在,因为解释器尚未完成app.py
的解析。一种可能的解决方案是移动在sockets
行以上app.py
初始化from admin_online import admin
的代码位。