Search code examples
pythonsocket.iopython-socketio

Print python-socketio events infos using decorators


I would like to improve the socketio.event decorator to make it print the event fired and its parameters. I have a Manager class which has a self.sio: socketio.Server attribute. I try to define a new decorator as a Manager method such as it returns a function decorated by self.sio.eventand which also prints its data. I have tried this solution, but it does not work :

    def event(self, func):
        @self.sio.event
        def wrapper(*args, **kwargs):
            print(f'[{func.__name__}] : {args} {kwargs}')
            func(*args, **kwargs)
        return wrapper

Any recommendation ?


Solution

  • I think something like this should work for you:

        def event(self, func):
            def wrapper(*args, **kwargs):
                print(f'[{func.__name__}] : {args} {kwargs}')
                return func(*args, **kwargs)
            return self.sio.on(func.__name__, wrapper)
    

    You can't really use the @sio.event on the wrapper, because then the event that will be configured is going to be named wrapper. My solution uses the @sio.on decorator, which accepts the event name explicitly.