From 3f9fda8f0de551567834400ff72a95c10c7d42b4 Mon Sep 17 00:00:00 2001 From: Miguel Grinberg Date: Sat, 8 Jun 2019 15:32:24 +0100 Subject: [PATCH] Add ConnectionRefusedError exception from python-socketio (Fixes #989) --- docs/index.rst | 17 +++++++++++++---- flask_socketio/__init__.py | 3 ++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index 2f39507f..2ea2eca9 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -314,16 +314,25 @@ Connection Events Flask-SocketIO also dispatches connection and disconnection events. The following example shows how to register handlers for them:: - @socketio.on('connect', namespace='/chat') + @socketio.on('connect') def test_connect(): emit('my response', {'data': 'Connected'}) - @socketio.on('disconnect', namespace='/chat') + @socketio.on('disconnect') def test_disconnect(): print('Client disconnected') -The connection event handler can optionally return ``False`` to reject the -connection. This is so that the client can be authenticated at this point. +The connection event handler can return ``False`` to reject the connection, or +it can also raise `ConectionRefusedError`. This is so that the client can be +authenticated at this point. When using the exception, any arguments passed to +the exception are returned to the client in the error packet. Examples:: + + from flask_socketio import ConnectionRefusedError + + @socketio.on('connect') + def connect(): + if not self.authenticate(request.args): + raise ConnectionRefusedError('unauthorized!') Note that connection and disconnection events are sent individually on each namespace used. diff --git a/flask_socketio/__init__.py b/flask_socketio/__init__.py index f86832f6..7b9f076f 100644 --- a/flask_socketio/__init__.py +++ b/flask_socketio/__init__.py @@ -15,10 +15,11 @@ 'install the latest version of python-socketio in its place.') sys.exit(1) -import socketio import flask from flask import _request_ctx_stack, json as flask_json from flask.sessions import SessionMixin +import socketio +from socketio.exceptions import ConnectionRefusedError from werkzeug.debug import DebuggedApplication from werkzeug.serving import run_with_reloader