Python Twisted: “Wait” for a variable to be populated with another event

I know that twisted will not “wait” ... I work with an XMPP client to exchange data with an external process. I am sending a request and should receive an appropriate response. I use sendMessage to send my request to the server. When the server responds to the onMessage method, it will receive it and check if it is a response to the request (not necessarily the one I'm looking for), and pushes any response on the stack. As a return to my sendRequest, I want to return the results, so I would like to add an answer to my request from the stack and return. I read about threads, iterations, callbacks and conventions, tried many examples, and no one works for me. So my sample code here is very limited pseudo code to illustrate my problem. Any advice is appreciated.

class Foo(FooMessageProtocol):
    def __init__(self, *args, **kwargs):
        self.response_stack = dict()
        super(Foo, self).__init__(*args, **kwargs)    


    def sendRequest(self, data):
        self.sendMessage(id, data)
        # I know that this doesn't work, just to illustrate what I would like to do:
        while 1: 
            if self.response_stack.has_key(id):
               break
               return self.response_stack.pop(id) 


    def receiveAnswers(self, msg):
        response = parse(msg)
        self.response_stack[response['id']] = response
+3
1

sendRequest, sendRequest . make sendRequest a Deferred , .

, , sendRequest, , , .

- ():

class Foo(FooMessageProtocol):
    def __init__(self, *args, **kwargs):
        self._deferreds = {}
        super(Foo, self).__init__(*args, **kwargs)    

    def sendRequest(self, data):
        self.sendMessage(id, data)
        d = self._deferreds[id] = defer.Deferred()
        return d

    def receiveAnswers(self, msg):
        response = parse(msg)
        id = response['id']
        if id in self._deferreds:
            self._deferreds.pop(id).callback(response)
+3

Source: https://habr.com/ru/post/1763097/


All Articles