可以用下面的代碼來訪問bilibili
importtornado.httpclienthttp_client = tornado.httpclient.HTTPClient()try:? ? response = http_client.fetch("http://www.bilibili.com/")printresponse.bodyexcepthttpclient.HTTPErrorase:print"Error:", ehttp_client.close()
看下輸出
嗶哩嗶哩彈幕視頻網(wǎng) - ( ゜- ゜)つロ? 乾杯~? - bilibili.......
恩是B站首頁沒錯
我們來解析一下上面的代碼
首先是http_client = tornado.httpclient.HTTPClient()
創(chuàng)建了一個HTTPClient實例
這個類有兩個函數(shù)
def fetch(self, request,**kwargs)
其中的request可以是一個HTTPRequest 的實例或者是一個url的字符串
返回的是HTTPResponse對象
HTTPRequest和HTTPResponse
這兩個類定義在httpclient.py 中 可以從源碼中看下是如何實現(xiàn)的
看下HTTPRequest的init(self)函數(shù):
def __init__(self, url, method="GET", headers=None, body=None,? ? ? ? ? ? ? ? auth_username=None, auth_password=None, auth_mode=None,? ? ? ? ? ? ? ? connect_timeout=None, request_timeout=None,? ? ? ? ? ? ? ? if_modified_since=None, follow_redirects=None,? ? ? ? ? ? ? ? max_redirects=None, user_agent=None, use_gzip=None,? ? ? ? ? ? ? ? network_interface=None, streaming_callback=None,? ? ? ? ? ? ? ? header_callback=None, prepare_curl_callback=None,? ? ? ? ? ? ? ? proxy_host=None, proxy_port=None, proxy_username=None,? ? ? ? ? ? ? ? proxy_password=None, allow_nonstandard_methods=None,? ? ? ? ? ? ? ? validate_cert=None, ca_certs=None,? ? ? ? ? ? ? ? allow_ipv6=None,? ? ? ? ? ? ? ? client_key=None, client_cert=None, body_producer=None,? ? ? ? ? ? ? ? expect_100_continue=False, decompress_response=None):
我們來看下關(guān)鍵的參數(shù)
url? 鏈接參數(shù)
method? 如POST GET 默認為GET
headers 請求的額外頭? 可以是HTTPHeader 狠持,也可以是個dict
HTTPResponse定義了許多字段
request: 是一個HTTPRequest 的實例
code: http狀態(tài)碼? e.g. 200 or 404
reason: OK ERROR 什么的? 原因解釋
headers:響應(yīng)頭 是一個 tornado.httputil.HTTPHeaders 實例
effective_url: 經(jīng)過重定向之后的網(wǎng)址
body: response body as string (created on demand from self.buffer)
error: 如果出錯 則存在Exception 的實例,
request_time: 整個過程所消耗的時間 秒為單位
異步客戶端
class tornado.httpclient.AsyncHTTPClient
下面這段代碼和開頭代碼的效果是一樣的
defhandle_request(response):ifresponse.error:print"Error:", response.errorelse:printresponse.bodyhttp_client = tornado.httpclient.AsyncHTTPClient()http_client.fetch("http://www.bilibili.com/", handle_request)tornado.ioloop.IOLoop.instance().start()
題目之間的區(qū)別在于,前者要等待 完成整個請求钦幔,期間cpu是不干任何事的
而后者發(fā)出請求后將繼續(xù)做其他事情峰搪,請求完成后會產(chǎn)生時間來執(zhí)行handle_request這個函數(shù)
既所謂回調(diào)函數(shù) ,和cpu的interrupt機制一樣彩掐,提高效率的方法
文/金發(fā)萌音(簡書作者)
原文鏈接:http://www.reibang.com/p/75b466b81c5b
著作權(quán)歸作者所有柔昼,轉(zhuǎn)載請聯(lián)系作者獲得授權(quán)垂券,并標(biāo)注“簡書作者”。