Getting value of `event_type` inside wrapped method

Hello again!

I've switched to events for many things now, and it's great!

I'm using an RPC call to collect results, and store them. Which is also
great.

When I create an event handler, I give it a name that makes sense to me,
and then I 'send' that name as part of the payload to the results method.

A contrived example:

    @event_handler('source.service', 'do.stuff.now')
    def do_stuff_event(self, event):
        self.result.store('do.stuff.now', event)

It seems redundant to have `do.stuff.now` typed out twice - so is there a
'good' way to re-use the event_type declared in the wrapper?

Many thanks,

Geoff

Once again - I changed how I was 'seeing' the problem, and a different
(more elegant) solution proposed itself :slight_smile:

Hey Geoff,

I think this is one of the places where the Nameko design is less than
optimal. It would be better if the handling method could inspect the event
type it was handling, but unfortunately it just receives the payload. It's
annoying, but not worth breaking backwards compatibility to change.

You can work around it by subclassing the EventHander entrypoint and
overriding how it handles the incoming message:

# entrypoints.py

from nameko.events import EventHandler as NamekoEventHandler

class EventHandler(NamekoEventHandler):
    def handle_message(self, body, message):
        args = (self.event_type, body,) # add event type as first arg
        kwargs = {}

        context_data = self.unpack_message_headers(message)

        handle_result = partial(self.handle_result, message)
        try:
            self.container.spawn_worker(self, args, kwargs,
                                        context_data=context_data,
                                        handle_result=handle_result)
        except ContainerBeingKilled:
            self.queue_consumer.requeue_message(message)

event_handler = EventHander.decorator

# service.py

from .entrypoints import event_handler

class Service:
    
    @event_handler('service-name', 'event-type')
    def handle(self, event_type, event_payload):
        ...

What was your alternative solution? :wink:

ยทยทยท

On Thursday, November 16, 2017 at 4:44:17 PM UTC, juko...@gmail.com wrote:

Once again - I changed how I was 'seeing' the problem, and a different
(more elegant) solution proposed itself :slight_smile:

Nice. I'll take a look at that!

Nothing fancy - I just moved all of my strings to a config file, and pull
them in where needed. The nice thing is I can override the values with
enviroment variables now (`os.environ.get('event_name',
'default_event_name')`).

Early in my programming adventure, someone drilled into me that "having
strings inside function code creates a maintenance nightmare" and I've
never been able to shift it. So I try to declare string and use the
variable.

Still loving Nameko. The Event system most of all - and I wasn't even
looking for that!