如何在另一个内部延迟(级联延迟)执行HTTP Get请求?

时间:2016-05-30 14:00:25

标签: python twisted deferred

我想做一个GET请求来检查返回代码是否符合我的预期。此请求发生在由一般延迟链的addCallback调用的函数内,如下面的代码所示。

我的具体问题如果:如何返回-D-行到达-E行?

似乎回调函数" cbResponse" (行-D-)永远不会被调用。我的第一次尝试是执行请求并返回请求结果的回调链(行-A-)。它失败了,因为deferr对象没有属性结果。 第二次尝试(行-B-),返回延迟对象本身。它也没有返回结果。 第三次尝试(行-C-),返回任何内容,但它显然没有请求的响应代码。

非常感谢!

from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.internet import reactor, defer

class Test (object):


    @classmethod
    def getRequest (self, result):

        print "Function getRequest"

        agent = Agent(reactor)

        d2 = agent.request('GET',
                           'http://www.google.com',
                           Headers({'User-Agent': ['Twisted Web Client Example']}),
                           None)

        d2.addCallback(Test.cbResponse)

        # 1 st attempt: return the result of d2. Fail: exceptions.AttributeError: Deferred instance has no attribute 'result'
        return d2.result            # --> line A

        # 2nd attempt: return only the deferr object d2. Don't fail, but I can't get the result of the above request
        ### return d2                   # --> line B

        # 3rd attemp: return None (without return). 
                                    # --> line C   

    @classmethod
    def cbResponse(response):

        print 'Function cbResponse %s', response.code
        # This is the return value I want to pass back to deferredChain function (called at line E)
        return response.code            # line --> D

    @classmethod
    def deferredChain(self):
        d = defer.Deferred()

        d.addCallback(Test.getRequest)  # line --> E
        d.callback("success")

        return d.result                 # line --> F



if __name__ == '__main__':
    tst = Test()
    rtn = tst.deferredChain()
    print "RTN: %s " % rtn

2 个答案:

答案 0 :(得分:0)

您正在使用Twisted Agent,这需要运行reactor才能正常工作,请参阅文档中的链接示例。如果启动Twisted reactor,您的代码示例将正常工作。

if __name__ == '__main__':
    tst = Test()
    rtn = tst.deferredChain()
    reactor.run()
    print "RTN: %s " % rtn

Twisted Treq是一个构建在代理之上的有趣框架,它承诺为您提供类似于Twisted异步HTTP客户端的API的python请求。

答案 1 :(得分:0)

您正在同步调用tst.deferredChain()并尝试读取其中的d.result,这是不正确的。正确的解决方案是让它返回延迟并附加回调。

相关问题