You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask集成SocketIO启动报错:UnboundLocalError问题求助

Fixing UnboundLocalError with Flask-SocketIO and Gevent

Hey there, let's figure out why your Flask-SocketIO setup is throwing that error and get your app running smoothly again!

What's Causing the Issue?

The UnboundLocalError: local variable 'ssl_socket' referenced before assignment error stems from a compatibility bug between older versions of gevent (the server library Flask-SocketIO relies on) and your Python 2.7 environment. In older gevent releases, when handling non-SSL connections, the code tries to close a variable ssl_socket that was never initialized, triggering this crash.

Step-by-Step Fixes

1. Upgrade Dependencies to Resolve Gevent Bug

First, let's update the libraries causing the conflict. Run one of these commands based on your package manager:

  • Using pip:
    pip install --upgrade gevent gevent-websocket flask-socketio
    
  • Using conda (since you're on Anaconda2):
    conda install -c conda-forge --upgrade gevent gevent-websocket flask-socketio
    

2. Fix the Debug Mode Typo

In your Flask code, you used Debug=True in socketio.run()—Python is case-sensitive, so this won't enable debug mode correctly. Change it to lowercase:

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', debug=True)

3. Align Frontend and Backend Socket Namespaces

Your backend defines the plz reload event under the /test namespace, but your frontend connects to the default namespace. To fix this, pick one of these options:

  • Option 1: Update your frontend to connect to the /test namespace:
    $(document).ready(function(){
        var socket = io.connect('http://localhost:5000/test');
        socket.on('connect', function() {
            socket.emit('my event', {data: 'I\'m connected!'});
        });
        socket.on('reload', function(msg) {
            $('#log').append('<p>Received: ' + msg.data + '</p>');
            location.reload();
        });
    });
    
  • Option 2: Remove the namespace from your backend event if you don't need it:
    @socketio.on('plz reload')  # Removed namespace='/test'
    def test_message(message):
        emit('reload', {'data': message['data']})
    

Verify the Fix

After applying these changes, restart your Flask app. Visit localhost:5000—the page should load without errors, and your SocketIO events should work as expected.

内容的提问来源于stack exchange,提问作者Hairy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:28:05