Twisted:如何知道何时收到所有数据?

2024-09-30 02:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

self.agent = Agent(reactor, pool=pool)
self.deferred = self.agent.request(
            'GET',
            self.url,
            Headers({'User-Agent': ['Mozilla/5.0']})
        )

self.deferred.addCallback(self.gotResponse)

但gotResponse对接收到的数据的每一部分都进行了调用,而不是针对所有数据。我可以收集,但怎么知道我得到了所有的数据?在

编辑:

我找到了this(来自单词“如果响应体已完全接收到”),但仍然不知道如何实现这一点。我的意思是,“失败会结束”是什么意思?在


Tags: 数据selfurlmozillagetrequestagentheaders
3条回答

我没有足够的知识和扭曲给你一个正确的答案。。。但我可以指出一些好的方向。在

使用twisted deferreds,您可以创建一系列回调(成功)和errback(失败)链,这些回调在完成时触发。在

在你的例子中-我不知道是什么自我代理请求或者为什么它会返回部分数据。这听起来并不完全正确,但通常我会用封装在延迟信号服务中的阻塞代码来获取url。在

但是,基于您的代码,我想建议两件事:

a-请阅读此处的延迟http://twistedmatrix.com/documents/current/core/howto/defer.html

b-您需要添加一个errback来处理错误请求。关于“包装”的文本必须处理这样一个事实:twisted并没有真正引发错误,相反,它允许您定义要运行的errback,并且您可以在这些错误中捕获错误。有更好的twisted技术的人可以更好地解释这一点,但是由于延迟是异步的,所以您需要这样一种机制来有效地处理错误。在

class YourExample(object):
    def your_example(self):
        self.agent = Agent(reactor, pool=pool)
        self.deferred = self.agent.request(
                'GET',
                self.url,
                Headers({'User-Agent': ['Mozilla/5.0']})
            )

        self.deferred.addCallback(self.gotResponse).addErrback(self.gotBadResponse)

def gotBadResponse(self,raised):
    """you might have cleanup code here, or mark the url as bad in the database, or something similar"""
    pass

在twisted 13.1.0中,您可以使用readBody()。从 http://twistedmatrix.com/documents/13.1.0/api/twisted.web.client.readBody.html,“这是一个帮助函数,用于不希望增量接收HTTP响应主体的客户端。”

从回调函数调用readBody(),在上面的示例中,dataReceived()处理数据,readBody()返回一个延迟的回调函数,您可以附加另一个回调函数来获取整个正文作为参数。在

嗯, 雷沙德。在

twisted文档提供了一个如何做到这一点的示例。在

来自http://twistedmatrix.com/documents/current/web/howto/client.html

from pprint import pformat

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

class BeginningPrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.remaining = 1024 * 10

    def dataReceived(self, bytes):
        if self.remaining:
            display = bytes[:self.remaining]
            print 'Some data received:'
            print display
            self.remaining -= len(display)

    def connectionLost(self, reason):
        print 'Finished receiving body:', reason.getErrorMessage()
        self.finished.callback(None)

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

def cbRequest(response):
    print 'Response version:', response.version
    print 'Response code:', response.code
    print 'Response phrase:', response.phrase
    print 'Response headers:'
    print pformat(list(response.headers.getAllRawHeaders()))
    finished = Deferred()
    response.deliverBody(BeginningPrinter(finished))
    return finished
d.addCallback(cbRequest)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

请求完成后,将调用BeginningPrinter的connectionLost()方法。在

^{pr2}$

看起来,检查if reason.check(twisted.web.client.ResponseDone)将告诉您它是否成功。在

相关问题 更多 >

    热门问题