From f4ebcc798df28a0b9c91eb0b53ec3754a3ecdb3e Mon Sep 17 00:00:00 2001 From: Miguel Grinberg Date: Fri, 10 May 2024 00:00:41 +0100 Subject: [PATCH] Handle events with catch-all namespace (Fixes #2061) --- src/flask_socketio/__init__.py | 8 +++++++- test_socketio.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/flask_socketio/__init__.py b/src/flask_socketio/__init__.py index c065ae3..494680f 100644 --- a/src/flask_socketio/__init__.py +++ b/src/flask_socketio/__init__.py @@ -279,7 +279,13 @@ def handle_my_custom_event(json): def decorator(handler): @wraps(handler) def _handler(sid, *args): - return self._handle_event(handler, message, namespace, sid, + nonlocal namespace + real_ns = namespace + if namespace == '*': + real_ns = sid + sid = args[0] + args = args[1:] + return self._handle_event(handler, message, real_ns, sid, *args) if self.server: diff --git a/test_socketio.py b/test_socketio.py index 7223dc5..49895a3 100644 --- a/test_socketio.py +++ b/test_socketio.py @@ -182,6 +182,11 @@ def on_changing_response(): return data +@socketio.on('wildcard', namespace='*') +def wildcard(data): + emit('my custom response', data) + + @socketio.on_error() def error_handler(value): if isinstance(value, AssertionError): @@ -416,6 +421,16 @@ def test_send_json_namespace(self): self.assertEqual(len(received), 1) self.assertEqual(received[0]['args']['a'], 'b') + def test_send_catch_all_namespace(self): + client = socketio.test_client(app, namespace='/test') + client.get_received('/test') + client.emit('wildcard', {'a': 'b'}, namespace='/test') + received = client.get_received('/test') + self.assertEqual(len(received), 1) + self.assertEqual(len(received[0]['args']), 1) + self.assertEqual(received[0]['name'], 'my custom response') + self.assertEqual(received[0]['args'][0]['a'], 'b') + def test_emit(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received()