国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python三方庫之requests的快速上手

2020-01-04 13:34:21
字體:
供稿:網(wǎng)友

本文基于2.21.0

發(fā)送請(qǐng)求

發(fā)送GET請(qǐng)求:

r = requests.get('https://api.github.com/events')

發(fā)送POST請(qǐng)求:

r = requests.post('https://httpbin.org/post', data={'key':'value'})

其他請(qǐng)求接口與HTTP請(qǐng)求類型一致,如PUT, DELETE, HEAD, OPTIONS等。

在URL查詢字符串中使用參數(shù)

給params參數(shù)傳遞一個(gè)字典對(duì)象:

>>> payload = {'key1': 'value1', 'key2': 'value2'}>>> r = requests.get('https://httpbin.org/get', params=payload)>>> print(r.url)https://httpbin.org/get?key2=value2&key1=value1

字典的值也可以是一個(gè)列表:

>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}>>> r = requests.get('https://httpbin.org/get', params=payload)>>> print(r.url)https://httpbin.org/get?key1=value1&key2=value2&key2=value3

參數(shù)中值為None的鍵值對(duì)不會(huì)加到查詢字符串

文本響應(yīng)內(nèi)容

Response對(duì)象的text屬性可以獲取服務(wù)器響應(yīng)內(nèi)容的文本形式,Requests會(huì)自動(dòng)解碼:

>>> r = requests.get('https://api.github.com/events')>>> r.text'[{"id":"9167113775","type":"PushEvent","actor"...

訪問Response.text時(shí),Requests將基于HTTP頭猜測(cè)響應(yīng)內(nèi)容編碼。使用Response.encoding屬性可以查看或改變Requests使用的編碼:

>>> r.encoding'utf-8'>>> r.encoding = 'ISO-8859-1'

二進(jìn)制響應(yīng)內(nèi)容

Response對(duì)象的content屬性可以獲取服務(wù)器響應(yīng)內(nèi)容的二進(jìn)制形式:

>>> r.contentb'[{"id":"9167113775","type":"PushEvent","actor"...

JSON響應(yīng)內(nèi)容

Response對(duì)象的json()方法可以獲取服務(wù)器響應(yīng)內(nèi)容的JSON形式:

>>> r = requests.get('https://api.github.com/events')>>> r.json()[{'repo': {'url': 'https://api.github.com/...

如果JSON解碼失敗,將拋出異常。

原始響應(yīng)內(nèi)容

在極少情況下,可能需要訪問服務(wù)器原始套接字響應(yīng)。通過在請(qǐng)求中設(shè)置stream=True參數(shù),并訪問Response對(duì)象的raw屬性實(shí)現(xiàn):

>>> r = requests.get('https://api.github.com/events', stream=True)>>> r.raw<urllib3.response.HTTPResponse object at 0x101194810>>>> r.raw.read(10)'/x1f/x8b/x08/x00/x00/x00/x00/x00/x00/x03'

通常的用法是用下面這種方式將原始響應(yīng)內(nèi)容保存到文件,Response.iter_content方法將自動(dòng)解碼gzip和deflate傳輸編碼:

with open(filename, 'wb') as fd:  for chunk in r.iter_content(chunk_size=128):    fd.write(chunk)

定制請(qǐng)求頭

傳遞一個(gè)dict對(duì)象到headers參數(shù),可以添加HTTP請(qǐng)求頭:

>>> url = 'https://api.github.com/some/endpoint'>>> headers = {'user-agent': 'my-app/0.0.1'}>>> r = requests.get(url, headers=headers)

定制的header的優(yōu)先級(jí)較低,在某些場(chǎng)景或條件下可能被覆蓋。

所有header的值必須是string, bytestring或unicode類型。但建議盡量避免傳遞unicode類型的值

更復(fù)雜的POST請(qǐng)求

發(fā)送form-encoded數(shù)據(jù)

給data參數(shù)傳遞一個(gè)字典對(duì)象:

>>> payload = {'key1': 'value1', 'key2': 'value2'}>>> r = requests.post("https://httpbin.org/post", data=payload)

如果有多個(gè)值對(duì)應(yīng)一個(gè)鍵,可以使用由元組組成的列表或者值是列表的字典:

>>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]>>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)>>> payload_dict = {'key1': ['value1', 'value2']}>>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)

發(fā)送非form-encoded數(shù)據(jù)

如果傳遞的是字符串而非字典,將直接發(fā)送該數(shù)據(jù):

>>> import json>>> url = 'https://api.github.com/some/endpoint'>>> payload = {'some': 'data'}>>> r = requests.post(url, data=json.dumps(payload))

或者可以使用json參數(shù)自動(dòng)對(duì)字典對(duì)象編碼:

>>> url = 'https://api.github.com/some/endpoint'>>> payload = {'some': 'data'}>>> r = requests.post(url, json=payload)

a) 如果在請(qǐng)求中使用了data或files參數(shù),json參數(shù)會(huì)被忽略。b) 在請(qǐng)求中使用json參數(shù)會(huì)改變Content-Type的值為application/json

POST一個(gè)多部分編碼(Multipart-Encoded)的文件

上傳文件:

>>> url = 'https://httpbin.org/post'>>> files = {'file': open('report.xls', 'rb')}>>> r = requests.post(url, files=files)

顯式地設(shè)置文件名,內(nèi)容類型(Content-Type)以及請(qǐng)求頭:

>>> url = 'https://httpbin.org/post'>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}>>> r = requests.post(url, files=files)

甚至可以發(fā)送作為文件接收的字符串:

>>> url = 'http://httpbin.org/post'>>> files = {'file': ('report.csv', 'some,data,to,send/nanother,row,to,send/n')}>>> r = requests.post(url, files=files)

如果發(fā)送的文件過大,建議使用第三方包requests-toolbelt做成數(shù)據(jù)流。

強(qiáng)烈建議以二進(jìn)制模式打開文件,因?yàn)镽equests可能以文件中的字節(jié)長(zhǎng)度來設(shè)置Content-Length

響應(yīng)狀態(tài)碼

Response對(duì)象的status_code屬性可以獲取響應(yīng)狀態(tài):

>>> r = requests.get('https://httpbin.org/get')>>> r.status_code200

requests庫還內(nèi)置了狀態(tài)碼以供參考:

>>> r.status_code == requests.codes.okTrue

如果請(qǐng)求異常(狀態(tài)碼為4XX的客戶端錯(cuò)誤或5XX的服務(wù)端錯(cuò)誤),可以調(diào)用raise_for_status()方法拋出異常:

>>> bad_r = requests.get('https://httpbin.org/status/404')>>> bad_r.status_code404>>> bad_r.raise_for_status()Traceback (most recent call last): File "requests/models.py", line 832, in raise_for_status  raise http_errorrequests.exceptions.HTTPError: 404 Client Error

響應(yīng)頭

Response對(duì)象的headers屬性可以獲取響應(yīng)頭,它是一個(gè)字典對(duì)象,鍵不區(qū)分大小寫:

>>> r.headers{  'content-encoding': 'gzip',  'transfer-encoding': 'chunked',  'connection': 'close',  'server': 'nginx/1.0.4',  'x-runtime': '148ms',  'etag': '"e1ca502697e5c9317743dc078f67693f"',  'content-type': 'application/json'}>>> r.headers['Content-Type']'application/json'>>> r.headers.get('content-type')'application/json'

Cookies

Response對(duì)象的cookies屬性可以獲取響應(yīng)中的cookie信息:

>>> url = 'http://example.com/some/cookie/setting/url'>>> r = requests.get(url)>>> r.cookies['example_cookie_name']'example_cookie_value'

使用cookies參數(shù)可以發(fā)送cookie信息:

>>> url = 'https://httpbin.org/cookies'>>> cookies = dict(cookies_are='working')>>> r = requests.get(url, cookies=cookies)

Response.cookies返回的是一個(gè)RequestsCookieJar對(duì)象,跟字典類似但提供了額外的接口,適合多域名或多路徑下使用,也可以在請(qǐng)求中傳遞:

>>> jar = requests.cookies.RequestsCookieJar()>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')>>> url = 'https://httpbin.org/cookies'>>> r = requests.get(url, cookies=jar)>>> r.text'{"cookies": {"tasty_cookie": "yum"}}'

重定向及請(qǐng)求歷史

requests默認(rèn)對(duì)除HEAD外的所有請(qǐng)求執(zhí)行地址重定向。Response.history屬性可以追蹤重定向歷史,它返回一個(gè)list,包含為了完成請(qǐng)求創(chuàng)建的所有Response對(duì)象并由老到新排序。

下面是一個(gè)HTTP重定向HTTPS的用例:

>>> r = requests.get('http://github.com/')>>> r.url'https://github.com/'>>> r.status_code200>>> r.history[<Response [301]>]

使用allow_redirects參數(shù)可以禁用重定向:

>>> r = requests.get('http://github.com/', allow_redirects=False)>>> r.status_code301>>> r.history[]

如果使用的是HEAD請(qǐng)求,也可以使用allow_redirects參數(shù)允許重定向:

>>> r = requests.head('http://github.com/', allow_redirects=True)>>> r.url'https://github.com/'>>> r.history[<Response [301]>]

請(qǐng)求超時(shí)

使用timeout參數(shù)設(shè)置服務(wù)器返回響應(yīng)的最大等待時(shí)間:

>>> requests.get('https://github.com/', timeout=0.001)Traceback (most recent call last): File "<stdin>", line 1, in <module>requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

錯(cuò)誤及異常

  • ConnectionError:網(wǎng)絡(luò)異常,比如DNS錯(cuò)誤,連接拒絕等。
  • HTTPError:如果請(qǐng)求返回4XX或5XX狀態(tài)碼,調(diào)用Response.raise_for_status()會(huì)拋出此異常。
  • Timeout:連接超時(shí)。
  • TooManyRedirects:請(qǐng)求超過配置的最大重定向數(shù)。
  • RequestException:異常基類。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到python教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 寿宁县| 枣庄市| 驻马店市| 柏乡县| 南城县| 陆良县| 疏附县| 新竹县| 都匀市| 二连浩特市| 宜宾市| 清河县| 萍乡市| 会同县| 福泉市| 贵阳市| 璧山县| 炎陵县| 醴陵市| 樟树市| 保定市| 秦安县| 德钦县| 淮滨县| 武汉市| 嘉祥县| 锡林浩特市| 沙田区| 玛曲县| 清涧县| 永安市| 江油市| 天水市| 凤阳县| 同德县| 曲阳县| 湟源县| 赤壁市| 宝应县| 尤溪县| 托里县|