Twisted如何在客户端获得响应?

时间:2017-11-26 15:59:08

标签: python response twisted webclient

我正在阅读Twisted Network Programming Essentials。在第5章中,有这段代码:

# encoding: utf-8
import sys

from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent

class ResourcePrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished

    def dataReceived(self, data):
        '''
        data seems comes from response not transport
        '''
        print data

    def connectionLost(self, reason):
        self.finished.callback(None) # Fire with None, no callback in deferred: finished


def printResource(response):
    finished = Deferred()
    print "idf: ", id(finished)
    # Dispatch IProtocol to handle response
    response.deliverBody(ResourcePrinter(finished))
    return finished

def printError(failure):
    print >> sys.stderr, failure

def stop(result):
    print type(result) # Result is None, not return value from printResource, why?
    reactor.stop()


if len(sys.argv) != 2:
    print >> sys.stderr, "Usage: python e5-3.py URL"
    exit(1)

agent = Agent(reactor)
d = agent.request("GET", sys.argv[1])
d.addCallbacks(printResource, printError)
d.addBoth(stop)

reactor.run()
  1. 为什么有两个延期? →dfinished,它们是如何组合的?
  2. printResource的返回值是finished,为什么不传递给回调停止? (arg结果为None。)
  3. 响应的流程是什么,它的开始和结束位置是什么?流程似乎是,d以块的形式获取响应并将其传递给回调printResource。在printResource中,它会调度到IProtocol来处理它。它是如何工作的?通常,IProtocol会从ITransport接收数据,但此处似乎没有。

0 个答案:

没有答案