Skip to content

Commit

Permalink
Added non-decorator format for Server.on()
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Jun 29, 2015
1 parent 584aba2 commit 2d8d41c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 21 deletions.
45 changes: 24 additions & 21 deletions engineio/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,44 +72,47 @@ def generate_id(self):
"""Generate a unique session id."""
return uuid.uuid4().hex

def on(self, event):
"""Decorator to register an event handler.
def on(self, event, handler=None):
"""Register an event handler.
:param event: The event name. Can be ``'connect'``, ``'message'`` or
``'disconnect'``.
:param handler: The function that should be invoked to handle the
event. When this parameter is not given, the method
acts as a decorator for the handler function.
Example usage::
# as a decorator:
@eio.on('connect')
def connect(sid, environ):
def connect_handler(sid, environ):
print('Connection request')
if environ['REMOTE_ADDR'] in blacklisted:
return False # reject
@eio.on('message')
def message(sid, msg):
# as a method:
def message_handler(sid, msg):
print('Received message: ', msg)
eio.send(sid, 'response')
@eio.on('disconnect')
def disconnect(sid):
print('Disconnected: ', sid)
The decorated function is registered as handler for the event. The
first argument in this function is the ``sid`` (session ID) for the
client. The ``'connect'`` event handler receives the WSGI environment
as a second argument, and can return ``False`` to reject the
connection. The ``'message'`` handler receives the message payload as a
second argument. The ``'disconnect'`` handler does not take a second
argument.
eio.on('message', message_handler)
The handler function receives the ``sid`` (session ID) for the
client as first argument. The ``'connect'`` event handler receives the
WSGI environment as a second argument, and can return ``False`` to
reject the connection. The ``'message'`` handler receives the message
payload as a second argument. The ``'disconnect'`` handler does not
take a second argument.
"""
if event not in self.event_names:
raise ValueError('Invalid event')

def decorator(f):
self.handlers[event] = f
return f
return decorator
def set_handler(handler):
self.handlers[event] = handler
return handler

if handler is None:
return set_handler
set_handler(handler)

def send(self, sid, data):
"""Send a message to a client.
Expand Down
2 changes: 2 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ def test_on_event(self):
@s.on('connect')
def foo():
pass
s.on('disconnect', foo)

self.assertEqual(s.handlers['connect'], foo)
self.assertEqual(s.handlers['disconnect'], foo)

def test_on_event_invalid(self):
s = server.Server()
Expand Down

0 comments on commit 2d8d41c

Please sign in to comment.