Search code examples
pythondjangostomp

Stomp.py how to return message from listener


I've already read this topic: Stomp.py return message from listener

But i still don't get how this works, and why there's no way to retrieve a message from the stomp object, or the listener directly?

If i can send a message via the send method, and If i can receive a message with an on_message listener method, why can't I return that message to my original function, so I could return it to the frontend?

So if i have:

class MyListener(object):
    def on_error(self, headers, message):
        print '>>> ' + message
    def on_message(self, headers, message):
        print '>>> ' + message

how could I return a message from the on_message method?

or could I do it somehow after the conn.subscribe(...) ??


Solution

  • Ok, I found a way myself. All you have to do, is a slight change of the listener class:

    class MyListener(object):
        msg_list = []
    
        def __init__(self):
            self.msg_list = []
    
        def on_error(self, headers, message):
            self.msg_list.append('(ERROR) ' + message)
    
        def on_message(self, headers, message):
            self.msg_list.append(message)
    

    And in the code, where u use stomp.py:

    conn = stomp.Connection()
    lst = MyListener()
    conn.set_listener('', lst)
    conn.start()
    conn.connect()
    conn.subscribe(destination='/queue/test', id=1, ack='auto')
    time.sleep(2)
    messages = lst.msg_list
    conn.disconnect()
    return render(request, 'template.html', {'messages': messages})