twisted - 如何限制 Twisted http 客户端的下载速率?

标签 twisted

有没有办法限制 Twisted http 客户端的下载速率?如果没有,在 Twisted 中实现此类客户端的最简单方法是什么?

最佳答案

Twisted 中的流控制最常使用 IProducer.pauseProducingIProducer.resumeProducing 实现。

您需要自己测量来自生产者的吞吐量,并在适当的时间调用 pauseProducingresumeProducing 以将带宽使用限制在您寻求的水平。

当您使用 IResponse.deliverBody 时,您提供的协议(protocol)将附加到提供 IProducer 的对象。当您暂停和恢复该对象时,您正在控制从网络读取响应主体的速率。

所以,例如:

class SlowDownloader(Protocol):
    def __init__(self, reactor):
        self.reactor = reactor

    def dataReceived(self, data):
        print 'Received', len(data), 'bytes'
        self.transport.pauseProducing()
        # Delay further reading so that the download proceeds at
        # 1kB/sec at the fastest.
        delay = len(data) / 1024.0
        self.reactor.callLater(delay, self.transport.resumeProducing)

requesting = agent.request(...)
def requested(response):
    response.deliverBody(SlowDownloader())
requesting.addCallback(requested)

这不是一个特别好的限速实现。如果调用 resumeProducing 和下一个 dataReceived 调用之间有很长的延迟,它可能会比您预期的要慢。不过,解决这个问题只是做一些更多基于时间的数学运算。

关于twisted - 如何限制 Twisted http 客户端的下载速率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20782687/

相关文章:

python - 简单协议(protocol)(如twisted.pb)与消息传递(AMQP/JMS)与Web服务(REST/SOAP)

python - 出现条件后停止 Twisted.internet 中的 react 器

python - Scrapy、Splash和连接被对方​​拒绝: 10061

python - 使用 sqlite 排序的并发队列实现(扭曲)?

openssl - 尝试使用此代码通过 TLS 运行 TLS 时,为什么会出现握手失败?

python - Python TUI 后端有哪些选项?

Python + Twisted + sqlanydb = abort()

Python 扭曲 : read from file and send as TCP server

python : why a method from super class not seen?

python - 高速公路网络套接字超时后如何重新连接?