httpx 快速入門

2022-07-26 09:47 更新

首先,從導(dǎo)入 HTTPX 開始:

>>> import httpx

現(xiàn)在,讓我們嘗試獲取一個(gè)網(wǎng)頁。

>>> r = httpx.get('https://httpbin.org/get')
>>> r
<Response [200 OK]>

同樣,要發(fā)出 HTTP POST 請(qǐng)求:

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

PUT、DELETE、HEAD 和 OPTIONS 請(qǐng)求都遵循相同的樣式:

>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})
>>> r = httpx.delete('https://httpbin.org/delete')
>>> r = httpx.head('https://httpbin.org/get')
>>> r = httpx.options('https://httpbin.org/get')

在 URL 中傳遞參數(shù)

要在請(qǐng)求中包含 URL 查詢參數(shù),請(qǐng)使用關(guān)鍵字:?params?

>>> params = {'key1': 'value1', 'key2': 'value2'}
>>> r = httpx.get('https://httpbin.org/get', params=params)

要查看值如何編碼到 URL 字符串中,我們可以檢查用于發(fā)出請(qǐng)求的結(jié)果 URL:

>>> r.url
URL('https://httpbin.org/get?key2=value2&key1=value1')

您還可以將項(xiàng)目列表作為值傳遞:

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

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

HTTPX 將自動(dòng)處理將響應(yīng)內(nèi)容解碼為 Unicode 文本的過程。

>>> r = httpx.get('https://www.example.org/')
>>> r.text
'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'

您可以檢查將用于解碼響應(yīng)的編碼。

>>> r.encoding
'UTF-8'

在某些情況下,響應(yīng)可能不包含顯式編碼,在這種情況下,HTTPX 將嘗試自動(dòng)確定要使用的編碼。

>>> r.encoding
None
>>> r.text
'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'

如果您需要覆蓋標(biāo)準(zhǔn)行為并顯式設(shè)置要使用的編碼,那么您也可以這樣做。

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

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

對(duì)于非文本響應(yīng),響應(yīng)內(nèi)容也能以字節(jié)的形式進(jìn)行訪問:

>>> r.content
b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'

任何?gzip?和?deflate ?HTTP響應(yīng)編碼都將自動(dòng)為您解碼。如果安裝了?brotli?,則也將支持?brotli?響應(yīng)編碼。

例如,要根據(jù)請(qǐng)求返回的二進(jìn)制數(shù)據(jù)創(chuàng)建圖片,可以使用以下代碼:

>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))

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

通常,Web API 響應(yīng)將編碼為 JSON。

>>> r = httpx.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ...  }}]

自定義headers

要在傳出請(qǐng)求中包含其他?headers?,請(qǐng)使用關(guān)鍵字參數(shù):?headers?

>>> url = 'https://httpbin.org/headers'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = httpx.get(url, headers=headers)

發(fā)送表單編碼數(shù)據(jù)

某些類型的 HTTP 請(qǐng)求(如 ?POST?和?PUT ?請(qǐng)求)可以在請(qǐng)求正文中包含數(shù)據(jù)。包含它的一種常見方法是作為表單編碼的數(shù)據(jù),用于HTML表單。

>>> data = {'key1': 'value1', 'key2': 'value2'}
>>> r = httpx.post("https://httpbin.org/post", data=data)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

表單編碼數(shù)據(jù)還可以包含來自給定鍵的多個(gè)值。

>>> data = {'key1': ['value1', 'value2']}
>>> r = httpx.post("https://httpbin.org/post", data=data)
>>> print(r.text)
{
  ...
  "form": {
    "key1": [
      "value1",
      "value2"
    ]
  },
  ...
}

發(fā)送分段文件上傳

您還可以使用 HTTP 分段編碼上傳文件:

>>> files = {'upload-file': open('report.xls', 'rb')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
{
  ...
  "files": {
    "upload-file": "<... binary content ...>"
  },
  ...
}

還可以通過使用項(xiàng)的元組作為文件值來顯式設(shè)置文件名和內(nèi)容類型:

>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
{
  ...
  "files": {
    "upload-file": "<... binary content ...>"
  },
  ...
}

如果需要在多部分表單中包含非文件數(shù)據(jù)字段,請(qǐng)使用以下參數(shù):??data=?...?

>>> data = {'message': 'Hello, world!'}
>>> files = {'file': open('report.xls', 'rb')}
>>> r = httpx.post("https://httpbin.org/post", data=data, files=files)
>>> print(r.text)
{
  ...
  "files": {
    "file": "<... binary content ...>"
  },
  "form": {
    "message": "Hello, world!",
  },
  ...
}

發(fā)送 JSON 編碼數(shù)據(jù)

如果您只需要一個(gè)簡單的鍵值數(shù)據(jù)結(jié)構(gòu),則表單編碼數(shù)據(jù)是可以的。對(duì)于更復(fù)雜的數(shù)據(jù)結(jié)構(gòu),您通常需要改用 JSON 編碼。

>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}
>>> r = httpx.post("https://httpbin.org/post", json=data)
>>> print(r.text)
{
  ...
  "json": {
    "boolean": true,
    "integer": 123,
    "list": [
      "a",
      "b",
      "c"
    ]
  },
  ...
}

發(fā)送二進(jìn)制請(qǐng)求數(shù)據(jù)

對(duì)于其他編碼,應(yīng)該使用?content=...?參數(shù),傳遞bytes 類型或生成?bytes?的生成器。

>>> content = b'Hello, world'
>>> r = httpx.post("https://httpbin.org/post", content=content)

您可能還希望在上傳二進(jìn)制數(shù)據(jù)時(shí)設(shè)置自定義標(biāo)頭?Content-Type?。

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

我們可以檢查響應(yīng)的 HTTP 狀態(tài)代碼:

>>> r = httpx.get('https://httpbin.org/get')
>>> r.status_code
200

HTTPX還包括一個(gè)簡單的快捷方式,用于通過文本短語訪問狀態(tài)代碼。

>>> r.status_code == httpx.codes.OK
True

我們可以為任何不是 ?2xx ?成功代碼的響應(yīng)提出異常:

>>> not_found = httpx.get('https://httpbin.org/status/404')
>>> not_found.status_code
404
>>> not_found.raise_for_status()
Traceback (most recent call last):
  File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status
    raise HTTPStatusError(message, response=self)
httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404
For more information check: https://httpstatuses.com/404

任何成功的響應(yīng)代碼將只是返回?None?,而不是引發(fā)異常。

>>> r.raise_for_status()

響應(yīng)標(biāo)頭

響應(yīng)標(biāo)頭可用作類似字典的接口。

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

數(shù)據(jù)類型不區(qū)分大小寫,因此?Headers?可以使用任意大小寫(大小寫不敏感)。

>>> r.headers['Content-Type']
'application/json'

>>> r.headers.get('content-type')
'application/json'

根據(jù) RFC 7230,單個(gè)響應(yīng)標(biāo)頭的多個(gè)值表示為單個(gè)逗號(hào)分隔值:

收件人可以將具有相同字段名稱的多個(gè)標(biāo)頭字段組合成一個(gè)“字段名稱:字段值”對(duì),而無需更改消息的語義,方法是按順序?qū)⒚總€(gè)后續(xù)字段值附加到組合的字段值中,并用逗號(hào)分隔。

流式處理響應(yīng)

對(duì)于大型下載,您可能希望使用不會(huì)一次將整個(gè)響應(yīng)正文加載到內(nèi)存中的流式處理響應(yīng)。

您可以流式傳輸響應(yīng)的二進(jìn)制內(nèi)容...

>>> with httpx.stream("GET", "https://www.example.com") as r:
...     for data in r.iter_bytes():
...         print(data)

或者回復(fù)的文本...

>>> with httpx.stream("GET", "https://www.example.com") as r:
...     for text in r.iter_text():
...         print(text)

或者逐行流式傳輸文本...

>>> with httpx.stream("GET", "https://www.example.com") as r:
...     for line in r.iter_lines():
...         print(line)

HTTPX 將使用通用行尾,將所有情況規(guī)范化為 ?\n?。

在某些情況下,您可能希望在不應(yīng)用任何 HTTP 內(nèi)容解碼的情況下訪問響應(yīng)上的原始字節(jié)。在這種情況下,Web 服務(wù)器已應(yīng)用的任何內(nèi)容編碼,如 ?gzip?、?deflate?或 ?brotli ?都不會(huì)自動(dòng)解碼。

>>> with httpx.stream("GET", "https://www.example.com") as r:
...     for chunk in r.iter_raw():
...         print(chunk)

如果以上述任何一種方式使用流式處理響應(yīng),則? response.content?和?response.text? 屬性將不可用,并且在訪問時(shí)將引發(fā)錯(cuò)誤。但是,您也可以使用響應(yīng)流式處理功能有條件地加載響應(yīng)正文:

>>> with httpx.stream("GET", "https://www.example.com") as r:
...     if r.headers['Content-Length'] < TOO_LONG:
...         r.read()
...         print(r.text)

Cookie

可以輕松訪問在響應(yīng)中設(shè)置的任何 Cookie:

>>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip')
>>> r.cookies['chocolate']
'chip'

要在傳出請(qǐng)求中包含 Cookie,請(qǐng)使用以下參數(shù):?cookies?

>>> cookies = {"peanut": "butter"}
>>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies)
>>> r.json()
{'cookies': {'peanut': 'butter'}}

Cookies在?Cookies?實(shí)例中返回,該實(shí)例是一種類似字典的數(shù)據(jù)結(jié)構(gòu),具有用于按域或路徑訪問 Cookie 的附加 API。

>>> cookies = httpx.Cookies()
>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')
>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')
>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.json()
{'cookies': {'cookie_on_domain': 'hello, there!'}}

重定向和歷史記錄

默認(rèn)情況下,HTTPX 不會(huì)遵循所有 HTTP 方法的重定向,盡管可以顯式啟用此功能。

例如,GitHub 將所有 HTTP 請(qǐng)求重定向到 HTTPS。

>>> r = httpx.get('http://github.com/')
>>> r.status_code
301
>>> r.history
[]
>>> r.next_request
<Request('GET', 'https://github.com/')>

您可以使用?follow_redirects?參數(shù)修改默認(rèn)重定向處理:

>>> r = httpx.get('http://github.com/', follow_redirects=True)
>>> r.url
URL('https://github.com/')
>>> r.status_code
200
>>> r.history
[<Response [301 Moved Permanently]>]

響應(yīng)的?history?屬性可用于檢查任何關(guān)注的重定向。它包含所遵循的任何重定向響應(yīng)的列表,按其創(chuàng)建順序排列。

超時(shí)

HTTPX 默認(rèn)為所有網(wǎng)絡(luò)操作包含合理的超時(shí),這意味著如果連接未正確建立,則它應(yīng)該始終引發(fā)錯(cuò)誤,而不是無限期掛起。

網(wǎng)絡(luò)不活動(dòng)的默認(rèn)超時(shí)為五秒。您可以將值修改為更嚴(yán)格:

>>> httpx.get('https://github.com/', timeout=0.001)

您還可以完全禁用超時(shí)行為...

>>> httpx.get('https://github.com/', timeout=None)

有關(guān)高級(jí)超時(shí)管理,請(qǐng)參閱超時(shí)設(shè)置。

認(rèn)證

HTTPX 支持基本和摘要式 HTTP 身份驗(yàn)證。

要提供基本的身份驗(yàn)證憑據(jù),請(qǐng)將一個(gè)2元組的純文本?str?或?bytes?對(duì)象作為?auth?參數(shù)傳遞給請(qǐng)求函數(shù):

>>> httpx.get("https://example.com", auth=("my_user", "password123"))

要為摘要身份驗(yàn)證提供憑據(jù),您需要實(shí)例化一個(gè)?DigestAuth?對(duì)象,并將明文用戶名和密碼作為參數(shù)。然后,可以將該對(duì)象作為?auth?參數(shù)傳遞給上述請(qǐng)求方法:

>>> auth = httpx.DigestAuth("my_user", "password123")
>>> httpx.get("https://example.com", auth=auth)
<Response [200 OK]>


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)