呆呆的等待所有回调完成

时间:2018-11-19 11:48:51

标签: python-2.7 twisted twisted.web

我有一个方法,可以使用twisted调用异步调用并返回一个值。我的要求是仅在所有回调完成后才返回。

from twisted.web import client
from twisted.internet import reactor, ssl
from OpenSSL import SSL
from twisted.web.http_headers import Headers
from twisted.internet import reactor
from twisted.web.client import Agent, readBody
import traceback

class sslPolicyForAgent(client.BrowserLikePolicyForHTTPS):
    def creatorForNetloc(self, hostname, port):
        return ssl.optionsForClientTLS(
            hostname.decode("ascii"),
            trustRoot=self._trustRoot
        )

class ReadData(object):
    def __init__(self, cred_data, security_resource_list):
        try:
            self.creds = cred_data
            self.securitycenter_list = security_resource_list
            self.callbackstack = list()
        except Exception as e:
            traceback.print_exc()

    def deferred_rest_api_call(self, url, num):
        try:
            agent = Agent(reactor, contextFactory=sslPolicyForAgent())
            deferred = agent.request(b'GET',url)
            return deferred
        except Exception as e:
            traceback.print_exc()

    def successCallback(self, result, num):
        print('Processing callback')
        print(result)

    def errorCallback(self, err):
        print('Error')

    def getDiscoveryResultListData(self):
        for num in range(0,2):
            self.url = 'https://www.google.com/'
            deferred = self.deferred_rest_api_call(self.url, num)
            deferred.addCallback(self.successCallback, num)
            deferred.addErrback(self.errorCallback)
        return 'Finished processing'

if __name__ == '__main__':
    data = dict()
    data['url'] = 'DemoLB'
    readDataObj = ReadData(data, list())
    value_ret = readDataObj.getDiscoveryResultListData()
    print(value_ret)
    reactor.run()

但是,正如预期的那样,由于调用是异步的,因此回调是在从方法返回后完成的。在回调完成之前,具有结果/块的方式是什么?

我正在使用python 2.7。

-巴拉

0 个答案:

没有答案