diff --git a/docs/index.rst b/docs/index.rst index 9e3772c4..0b9b3ad7 100755 --- a/docs/index.rst +++ b/docs/index.rst @@ -198,6 +198,19 @@ Flask-SocketIO can also deal with exceptions:: Error handler functions take the exception object as an argument. +The message and data arguments of the current request can also be inspected with the ``request.event`` variable, which is useful for error logging and debugging outside the event handler:: + + from flask import request + + @socketio.on("my error event") + def on_my_event(data): + raise RuntimeError() + + @socketio.on_error_default + def default_error_handler(e): + print request.event["message"] # "my error event" + print request.event["args"] # (data,) + Access to Flask's Context Globals --------------------------------- diff --git a/flask_socketio/__init__.py b/flask_socketio/__init__.py index 402c54a8..3a961cc2 100644 --- a/flask_socketio/__init__.py +++ b/flask_socketio/__init__.py @@ -152,6 +152,9 @@ def _dispatch_message(self, app, namespace, message, args=[]): return with app.request_context(namespace.environ): request.namespace = namespace + request.event = { + "message": message, + "args": args} for k, v in namespace.session.items(): session[k] = v ret = self.messages[namespace.ns_name][message](*args) diff --git a/test_socketio.py b/test_socketio.py index f5cbfed3..c03d974e 100644 --- a/test_socketio.py +++ b/test_socketio.py @@ -7,7 +7,7 @@ cov = coverage.coverage() cov.start() -from flask import Flask, session +from flask import Flask, session, request from flask.ext.socketio import SocketIO, send, emit, join_room, leave_room app = Flask(__name__) @@ -64,6 +64,13 @@ def on_custom_event(data): emit('my custom response', data) +@socketio.on('other custom event') +def get_request_event(data): + global request_event_data + request_event_data = request.event + emit('my custom response', data) + + @socketio.on('my custom namespace event', namespace='/test') def on_custom_event_test(data): emit('my custom namespace response', data, namespace='/test') @@ -245,6 +252,15 @@ def test_emit(self): self.assertTrue(received[0]['name'] == 'my custom response') self.assertTrue(received[0]['args'][0]['a'] == 'b') + def test_request_event_data(self): + client = socketio.test_client(app) + client.get_received() # clean received + global request_event_data + request_event_data = None + client.emit('other custom event', 'foo') + expected_data = {'message': 'other custom event', 'args' : ('foo',)} + self.assertTrue(request_event_data == expected_data) + def test_emit_namespace(self): client = socketio.test_client(app, namespace='/test') client.get_received('/test') # clean received