有没有办法限制 Twisted http 客户端的下载速率?如果没有,在 Twisted 中实现此类客户端的最简单方法是什么?
最佳答案
Twisted 中的流控制最常使用 IProducer.pauseProducing
和 IProducer.resumeProducing
实现。
您需要自己测量来自生产者的吞吐量,并在适当的时间调用 pauseProducing
和 resumeProducing
以将带宽使用限制在您寻求的水平。
当您使用 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/