2017-04-23 67 views
0

目前使用的API速率限制了我每10秒3000個請求。由於具有異步IO特性,我有10,000個使用Tornado獲取的網址。Python旋風速率限制AsyncHttpClient獲取

我該如何去執行速率限制以反映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() 

回答

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的變量,並對其進行減法。