flask_socket_io中报错RuntimeError: You need to use the eventlet server.

异常信息:

在这里插入图片描述

源代码:

# -*- coding:UTF-8 -*-

"""
 @ProjectName  : Coded 
 @FileName     : app
 @Description:  flask 推送消息给客户端
 @Time         : 2022/12/3 15:19
 @Author       : Qredsun
 """


from flask import Flask, render_template
from flask_socketio import SocketIO
from threading import Lock
import random

async_mode = None
# async_mode = 'threading'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()


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


@socketio.on('connect', namespace='/test_conn')
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)


def background_thread():
    while True:
        socketio.sleep(2)
        t = random.randint(1, 100)
        socketio.emit('server_response', {'data': t}, namespace='/test_conn')


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


if __name__ == '__main__':
    # socketio.run(app, debug=True)
    app.run(debug=True) # , use_reloader=False

问题分析:

RuntimeError: You need to use the eventlet server. See the Deployment section of the documentation for more information.
从异常信息中看是要求使用 eventlet server.,而我的代码中没有指定async_mode,即flask默认使用了eventlet

如果使用socketio的run,程序运行是没有问题的。查看源代码,发现在socketio初始化时,设置async_mode = 'threading'
在这里插入图片描述

解决方法:

  • 方法一
    指定async_modethreading即可

  • 方法二
    使用socketio的run方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值