【问题标题】:Python Tornado rate limiting AsyncHttpClient fetchPython Tornado 速率限制 AsyncHttpClient 获取
【发布时间】:2017-09-20 10:30:46
【问题描述】:

目前使用的 API 将我的速率限制为每 10 秒 3000 个请求。由于 Tornado 的异步 IO 特性,我有 10,000 个使用 Tornado 获取的 url。

如何实施速率限制以反映 API 限制?

from tornado import ioloop, httpclient

i = 0

def handle_request(response):
    print(response.code)
    global i
    i -= 1
    if i == 0:
        ioloop.IOLoop.instance().stop()

http_client = httpclient.AsyncHTTPClient()
for url in open('urls.txt'):
    i += 1
    http_client.fetch(url.strip(), handle_request, method='HEAD')
ioloop.IOLoop.instance().start()

【问题讨论】:

    标签: python httprequest tornado rate-limiting


    【解决方案1】:

    你可以查看i的值在3000个请求的区间中的什么位置。例如,如果i 介于 3000 和 6000 之间,您可以将每个请求的超时时间设置为 10 秒,直到 6000。在 6000 之后,只需将超时时间加倍。以此类推。

    http_client = AsyncHTTPClient()
    
    timeout = 10
    interval = 3000
    
    for url in open('urls.txt'):
        i += 1
        if i <= interval:
            # i is less than 3000
            # just fetch the request without any timeout
            http_client.fetch(url.strip(), handle_request, method='GET')
            continue # skip the rest of the loop
    
        if i % interval == 1:
            # i is now 3001, or 6001, or so on ...
            timeout += timeout # double the timeout for next 3000 calls
    
        loop = ioloop.IOLoop.current()
        loop.call_later(timeout, callback=functools.partial(http_client.fetch, url.strip(), handle_request, method='GET'))
    

    注意:我只用少量请求测试了这段代码。 i 的值可能会发生变化,因为您在 handle_request 函数中减去了 i。如果是这种情况,您应该维护另一个类似于i 的变量并对其执行减法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多