Why do I get "NameError: name 'self' is not defined"?

Why do I get "NameError: name 'self' is not defined"?

我正在使用以下代码使用 Flask 和 socketio 实现 Web 服务器。

app = Flask(__name__, static_url_path = '', static_folder = 'static', template_folder = 'templates')
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins = '*', ping_timeout = 10, ping_interval = 1)
CORS(app)

USE_ENCRYPTION = False

class Server():

    def __init__(self):
        pass
    
    @app.route("/", methods = ['GET'])
    def index():
        return render_template('index.html')
    
    @socketio.on('connect', namespace = '/home')
    def messaging():
        #print('User connected')
        pass

    @socketio.on('disconnect')
    def messagingOf():
        #print('User disconnected')
        pass

    @socketio.on('my recon', namespace = '/home')
    def getmes(message, methods = ['GET', 'POST']):
        self.SendMessageToClient('home event', messages.messages.home_page_message, '/home')

    
    def SendMessageToClient(self, event, message, namespace_):
        if (USE_ENCRYPTION):
            socketio.emit(event, crypto.Crypto.Encrypt(message), namespace = namespace_)
        else:
            socketio.emit(event, message, namespace = namespace_)
    
    def ReceiveMessageFromClient(self, message):
        if (USE_ENCRYPTION):
            return crypto.Crypto.Decrypt(message)
        return message

    def Start(self):
        socketio.run(app, host = '0.0.0.0', port = 5000, debug = False)

问题是我收到错误:

line 55, in getmes
    self.SendMessageToClient('home event', messages.messages.home_page_message, '/home')
NameError: name 'self' is not defined

如果我改为使用静态方法,它会起作用。例如:

@staticmethod
def SendMessageToClient(event, message, namespace_):
    if (USE_ENCRYPTION):
        socketio.emit(event, crypto.Crypto.Encrypt(message), namespace = namespace_)
    else:
        socketio.emit(event, message, namespace = namespace_)

Server.SendMessageToClient('home event', messages.messages.home_page_message, '/home')

为什么我会收到 NameError?另外,在这种情况下如何避免使用静态方法?

您是要使用 Class-Based Namespaces 吗?这似乎是允许方法保留 self 参数的方法。

我找到了这个 link 并重现了下面的代码:

class MyCustomNamespace(socketio.ClientNamespace):
    def on_connect(self):
        pass

    def on_disconnect(self):
        pass

    def on_my_event(self, data):
        self.emit('my_response', data)

sio.register_namespace(MyCustomNamespace('/chat'))

我对socketio一无所知,但在我看来,您从需要处理的事件中选择方法的名称。所有的方法都是普通的实例方法意味着它们必须有self参数,这意味着你可以通过self.

引用其他属性