How to dynamically create an event_handler

#1

I’m somewhat new to Python and Nameko, but I was wondering if it was possible to create event handlers dynamically. For example, I would want new services to be able to register with an existing service. That existing service would listen for new service events.

class ExistingService:
   name = "existingservice"
    @rpc
    def register_new_service(self, service_name, event_type):
        # How can I create a new event handler on ExistingService that will listen for service_name/event_type dynamically?

class NewService:
    name = "newservice"
    event_type = "newservice_event"
    service_rpc = RpcProxy('existingservice')

    def __init__(self):
        self.register_myself()

    def register_myself(self):
        self.service_rpc.register_new_service(self.name, self.event_type)
#2

You can’t do this with Nameko events out of the box.

But you could very easily implement this “dynamic handler” behaviour with the underlying Publisher and Consumer that are defined in nameko/messaging.py. Events are just a small abstraction on top of these — see how little code is in nameko/events.py

To implement an event handler that consumed events from a service with any name, I think you’d only need to change the routing key the consumer uses to bind to the events exchange from “servicename.methodname” to “*.methodname”.

#3

Thanks! I’ll try it out…