tornado總結11-AsyncHTTPClient使用HTTP代理

參考文檔

HTTPRequest AsyncHTTPClient.configure HTTP 599: Timeout in request queue 異常處理html

說明

tornado的AsyncHTTPClient做爲爬蟲客戶端使用起來很方便, 可是爲了應對網站的IP訪問限制,這個時候就須要使用IP代理機制了, AsyncHTTPClient通過簡單的配置就能夠使用HTTP代理來進行http訪問了, 正好結合tornado的異步機制,就能夠同時開多個鏈接去訪問不一樣的內容,提升爬取速度。python

不過在windows上因爲curl庫的關係,我沒有跑起來,本文的代碼能夠跑在linux下面。linux

代碼

AsyncHTTPClient使用HTTP代理

import tornado.ioloop
from tornado.httpclient import HTTPRequest, AsyncHTTPClient


@tornado.gen.coroutine
def send_requ():
    http_requ = HTTPRequest(
        url='http://www.baidu.com',
        method='GET',
        proxy_host = 'a.b.c.d',  # 配置HTTP代理的ip地址
        proxy_port = 1234, # 設置HTTP代理的端口
    )

    http_resp = yield AsyncHTTPClient().fetch(http_requ)

    #處理回覆消息。。。

if __name__ == "__main__":
    # 配置 AsyncHTTPClient
    AsyncHTTPClient.configure(
        "tornado.curl_httpclient.CurlAsyncHTTPClient",  # 必須配置這個否則沒法使用代理
        max_clients=600  # 客戶端池數量配置設大一點
    )

    tornado.ioloop.IOLoop.run_sync(send_requ)

AsyncHTTPClient禁止排隊超時

上面的那段代碼在程序啓動時會調用AsyncHTTPClient.configure將最大的可用客戶端數量設置爲600了,到達600以後全部待發送的請求都會進入排隊機制,可是該隊列裏面的請求有個排隊時間,若是超時tornado將會丟棄這個請求並給調用方拋出一個異常。web

tornado.httpclient.HTTPError: HTTP 599: Timeout in request queue

下面的代碼能夠讓AsyncHTTPClient排隊的請求不會超時windows

from tornado.httpclient import AsyncHTTPClient
from tornado.log import gen_log
from tornado.simple_httpclient import SimpleAsyncHTTPClient


class NoQueueTimeoutHTTPClient(SimpleAsyncHTTPClient):
    def fetch_impl(self, request, callback):
        key = object()

        self.queue.append((key, request, callback))
        self.waiting[key] = (request, callback, None)

        self._process_queue()

        if self.queue:
            gen_log.debug("max_clients limit reached, request queued. %d active, %d queued requests." % (
                len(self.active), len(self.queue)))

AsyncHTTPClient.configure(NoQueueTimeoutHTTPClient, max_clients=20)
相關文章
相關標籤/搜索