我正在阅读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()
d
和finished
,它们是如何组合的?printResource
的返回值是finished
,为什么不传递给回调停止? (arg结果为None
。)d
以块的形式获取响应并将其传递给回调printResource
。在printResource
中,它会调度到IProtocol
来处理它。它是如何工作的?通常,IProtocol
会从ITransport
接收数据,但此处似乎没有。