開發者介面

此文件部分涵蓋 Requests 的所有介面。對於 Requests 依賴外部函式庫的部分,我們在此記錄最重要的內容,並提供連到標準文件的連結。

主要介面

Requests 的所有功能都可以透過這 7 種方法存取。它們都會回傳 Response 物件的實例。

requests.request(method, url, **kwargs)[原始碼]

建構並發送 Request

參數:
  • method – 新 Request 物件的方法:GETOPTIONSHEADPOSTPUTPATCHDELETE

  • url – 新 Request 物件的 URL。

  • params – (選填) 字典、元組列表或位元組,用於在 Request 的查詢字串中發送。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • json – (選填) 可 JSON 序列化的 Python 物件,用於在 Request 的 body 中發送。

  • headers – (選填) HTTP 標頭字典,與 Request 一起發送。

  • cookies – (選填) Dict 或 CookieJar 物件,與 Request 一起發送。

  • files – (選填) 'name': 類檔案物件' (或 {'name': 檔案元組}) 的字典,用於多部分編碼上傳。檔案元組 可以是 2 元組 ('filename', fileobj)、3 元組 ('filename', fileobj, 'content_type') 或 4 元組 ('filename', fileobj, 'content_type', custom_headers),其中 'content_type' 是一個字串,定義給定檔案的內容類型,而 custom_headers 是一個類似字典的物件,包含要為檔案新增的額外標頭。

  • auth – (選填) Auth 元組,用於啟用 Basic/Digest/Custom HTTP Auth。

  • timeout (floattuple) – (選填) 等待伺服器發送資料的最長秒數,以 float 或 (連線逾時, 讀取逾時) 元組表示。

  • allow_redirects (bool) – (選填) 布林值。啟用/停用 GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD 重定向。預設為 True

  • proxies – (選填) 將協定對應到 Proxy URL 的字典。

  • verify – (選填) 布林值或字串。如果是布林值,則控制是否驗證伺服器的 TLS 憑證;如果是字串,則必須是 CA 憑證套件的路徑。預設為 True

  • stream – (選填) 如果為 False,則會立即下載回應內容。

  • cert – (選填) 如果是字串,則為 SSL 用戶端憑證檔案 (.pem) 的路徑。如果是元組,則為 ('cert', 'key') 對。

回傳值:

Response 物件

回傳類型:

requests.Response

用法

>>> import requests
>>> req = requests.request('GET', 'https://httpbin.org/get')
>>> req
<Response [200]>
requests.head(url, **kwargs)[原始碼]

發送 HEAD 請求。

參數:
  • url – 新 Request 物件的 URL。

  • **kwargsrequest 接受的選填引數。如果未提供 allow_redirects,則會將其設定為 False (與預設的 request 行為相反)。

回傳值:

Response 物件

回傳類型:

requests.Response

requests.get(url, params=None, **kwargs)[原始碼]

發送 GET 請求。

參數:
  • url – 新 Request 物件的 URL。

  • params – (選填) 字典、元組列表或位元組,用於在 Request 的查詢字串中發送。

  • **kwargsrequest 接受的選填引數。

回傳值:

Response 物件

回傳類型:

requests.Response

requests.post(url, data=None, json=None, **kwargs)[原始碼]

發送 POST 請求。

參數:
  • url – 新 Request 物件的 URL。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • json – (選填) 可 JSON 序列化的 Python 物件,用於在 Request 的 body 中發送。

  • **kwargsrequest 接受的選填引數。

回傳值:

Response 物件

回傳類型:

requests.Response

requests.put(url, data=None, **kwargs)[原始碼]

發送 PUT 請求。

參數:
  • url – 新 Request 物件的 URL。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • json – (選填) 可 JSON 序列化的 Python 物件,用於在 Request 的 body 中發送。

  • **kwargsrequest 接受的選填引數。

回傳值:

Response 物件

回傳類型:

requests.Response

requests.patch(url, data=None, **kwargs)[原始碼]

發送 PATCH 請求。

參數:
  • url – 新 Request 物件的 URL。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • json – (選填) 可 JSON 序列化的 Python 物件,用於在 Request 的 body 中發送。

  • **kwargsrequest 接受的選填引數。

回傳值:

Response 物件

回傳類型:

requests.Response

requests.delete(url, **kwargs)[原始碼]

發送 DELETE 請求。

參數:
  • url – 新 Request 物件的 URL。

  • **kwargsrequest 接受的選填引數。

回傳值:

Response 物件

回傳類型:

requests.Response

例外

exception requests.RequestException(*args, **kwargs)[原始碼]

處理您的請求時發生不明確的例外。

exception requests.ConnectionError(*args, **kwargs)[原始碼]

發生連線錯誤。

exception requests.HTTPError(*args, **kwargs)[原始碼]

發生 HTTP 錯誤。

exception requests.URLRequired(*args, **kwargs)[原始碼]

需要有效的 URL 才能發出請求。

exception requests.TooManyRedirects(*args, **kwargs)[原始碼]

重新導向次數過多。

exception requests.ConnectTimeout(*args, **kwargs)[原始碼]

嘗試連線到遠端伺服器時,請求逾時。

產生此錯誤的請求可以安全地重試。

exception requests.ReadTimeout(*args, **kwargs)[原始碼]

伺服器未在規定的時間內發送任何資料。

exception requests.Timeout(*args, **kwargs)[原始碼]

請求逾時。

捕捉此錯誤將同時捕捉 ConnectTimeoutReadTimeout 錯誤。

exception requests.JSONDecodeError(*args, **kwargs)[原始碼]

無法將文字解碼為 json

請求 Session

class requests.Session[原始碼]

Requests 的 session。

提供 Cookie 持續性、連線池和組態。

基本用法

>>> import requests
>>> s = requests.Session()
>>> s.get('https://httpbin.org/get')
<Response [200]>

或作為上下文管理器

>>> with requests.Session() as s:
...     s.get('https://httpbin.org/get')
<Response [200]>
auth

預設的驗證元組或物件,附加到 Request

cert

SSL 用戶端憑證預設值。如果是字串,則為 SSL 用戶端憑證檔案 (.pem) 的路徑。如果是元組,則為 ('cert', 'key') 對。

close()[原始碼]

關閉所有 adapter,並因此關閉 session

cookies

一個 CookieJar,包含此 session 上目前所有未過期的 Cookie。預設情況下,它是一個 RequestsCookieJar,但也可能是任何其他相容於 cookielib.CookieJar 的物件。

delete(url, **kwargs)[原始碼]

發送 DELETE 請求。回傳 Response 物件。

參數:
  • url – 新 Request 物件的 URL。

  • **kwargsrequest 接受的選填引數。

回傳類型:

requests.Response

get(url, **kwargs)[原始碼]

發送 GET 請求。回傳 Response 物件。

參數:
  • url – 新 Request 物件的 URL。

  • **kwargsrequest 接受的選填引數。

回傳類型:

requests.Response

get_adapter(url)[原始碼]

為給定的 URL 回傳適當的連線 adapter。

回傳類型:

requests.adapters.BaseAdapter

get_redirect_target(resp)

接收 Response。回傳重新導向 URI 或 None

head(url, **kwargs)[原始碼]

發送 HEAD 請求。回傳 Response 物件。

參數:
  • url – 新 Request 物件的 URL。

  • **kwargsrequest 接受的選填引數。

回傳類型:

requests.Response

headers

不區分大小寫的標頭字典,將在從此 Session 發送的每個 Request 上發送。

hooks

事件處理 hook。

max_redirects

允許的最大重新導向次數。如果請求超過此限制,則會引發 TooManyRedirects 例外。預設值為 requests.models.DEFAULT_REDIRECT_LIMIT,即 30。

merge_environment_settings(url, proxies, stream, verify, cert)[原始碼]

檢查環境並將其與某些設定合併。

回傳類型:

dict

mount(prefix, adapter)[原始碼]

將連線 adapter 註冊到前綴。

Adapter 依前綴長度降序排序。

options(url, **kwargs)[原始碼]

發送 OPTIONS 請求。回傳 Response 物件。

參數:
  • url – 新 Request 物件的 URL。

  • **kwargsrequest 接受的選填引數。

回傳類型:

requests.Response

params

要附加到每個 Request 的查詢字串資料字典。字典值可以是列表,用於表示多值查詢參數。

patch(url, data=None, **kwargs)[原始碼]

發送 PATCH 請求。回傳 Response 物件。

參數:
  • url – 新 Request 物件的 URL。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • **kwargsrequest 接受的選填引數。

回傳類型:

requests.Response

post(url, data=None, json=None, **kwargs)[原始碼]

發送 POST 請求。回傳 Response 物件。

參數:
  • url – 新 Request 物件的 URL。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • json – (選填) 要在 Request 的 body 中發送的 json。

  • **kwargsrequest 接受的選填引數。

回傳類型:

requests.Response

prepare_request(request)[原始碼]

建構用於傳輸的 PreparedRequest 並回傳它。PreparedRequest 具有從 Request 實例和 Session 的設定合併而來的設定。

參數:

request – 要使用此 session 的設定準備的 Request 實例。

回傳類型:

requests.PreparedRequest

proxies

將協定或協定和主機對應到 Proxy URL 的字典 (例如 {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}),將用於每個 Request

put(url, data=None, **kwargs)[原始碼]

發送 PUT 請求。回傳 Response 物件。

參數:
  • url – 新 Request 物件的 URL。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • **kwargsrequest 接受的選填引數。

回傳類型:

requests.Response

rebuild_auth(prepared_request, response)

當重新導向時,我們可能希望從請求中移除驗證,以避免洩漏憑證。此方法會智慧地移除並重新應用驗證 (如果可能),以避免憑證遺失。

rebuild_method(prepared_request, response)

當重新導向時,我們可能希望根據某些規範或瀏覽器行為來變更請求的方法。

rebuild_proxies(prepared_request, proxies)

此方法透過考量環境變數來重新評估 Proxy 組態。如果我們重新導向到 NO_PROXY 涵蓋的 URL,我們會移除 Proxy 組態。否則,我們會為此 URL 設定遺失的 Proxy 金鑰 (以防它們被先前的重新導向移除)。

此方法也會在必要時替換 Proxy-Authorization 標頭。

回傳類型:

dict

request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)[source]

建構 Request、準備並發送它。傳回 Response 物件。

參數:
  • method – 新 Request 物件的方法。

  • url – 新 Request 物件的 URL。

  • params – (選填) 要在 Request 的查詢字串中發送的字典或位元組。

  • data – (選填) 字典、元組列表、位元組或類檔案物件,用於在 Request 的 body 中發送。

  • json – (選填) 要在 Request 的 body 中發送的 json。

  • headers – (選填) HTTP 標頭字典,與 Request 一起發送。

  • cookies – (選填) Dict 或 CookieJar 物件,與 Request 一起發送。

  • files – (選填) 用於多部分編碼上傳的 'filename': file-like-objects' 字典。

  • auth – (選填) 授權元組或可調用物件,以啟用基本/摘要/自訂 HTTP 授權。

  • timeout (floattuple) – (選填) 在放棄之前,等待伺服器發送資料的最長時間,以浮點數或 (連線逾時, 讀取逾時) 元組表示。

  • allow_redirects (bool) – (選填) 預設設定為 True。

  • proxies – (選填) 將協定或協定和主機名稱映射到代理 URL 的字典。

  • hooks – (選填) 將 Hook 名稱映射到一個事件或事件列表的字典,事件必須是可調用物件。

  • stream – (選填) 是否立即下載回應內容。預設為 False

  • verify – (選填) 布林值或字串。如果是布林值,則控制是否驗證伺服器的 TLS 憑證;如果是字串,則必須是 CA 捆綁包的路徑以供使用。預設為 True。當設定為 False 時,requests 將接受伺服器提供的任何 TLS 憑證,並將忽略主機名稱不符和/或過期的憑證,這將使您的應用程式容易受到中間人 (MitM) 攻擊。在本地開發或測試期間,將 verify 設定為 False 可能很有用。

  • cert – (選填) 如果是字串,則為 SSL 用戶端憑證檔案 (.pem) 的路徑。如果是元組,則為 ('cert', 'key') 對。

回傳類型:

requests.Response

resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)

接收 Response。傳回 Responses 或 Requests 的產生器。

send(request, **kwargs)[source]

發送給定的 PreparedRequest。

回傳類型:

requests.Response

should_strip_auth(old_url, new_url)

決定重新導向時是否應移除 Authorization 標頭

stream

串流回應內容預設值。

trust_env

信任環境設定以進行代理設定、預設驗證和類似操作。

verify

SSL 驗證預設值。預設為 True,要求 requests 驗證遠端 TLS 憑證。如果 verify 設定為 False,requests 將接受伺服器提供的任何 TLS 憑證,並將忽略主機名稱不符和/或過期的憑證,這將使您的應用程式容易受到中間人 (MitM) 攻擊。僅在測試時將此設定為 False

較低層級的類別

class requests.Request(method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None)[source]

使用者建立的 Request 物件。

用於準備 PreparedRequest,它會被發送到伺服器。

參數:
  • method – 要使用的 HTTP 方法。

  • url – 要發送的 URL。

  • headers – 要發送的標頭字典。

  • files – 要進行多部分上傳的 {filename: fileobject} 檔案字典。

  • data – 要附加到請求的主體。如果提供字典或元組列表 [(key, value)],將會進行表單編碼。

  • json – 要附加到請求主體的 JSON(如果未指定 files 或 data)。

  • params – 要附加到 URL 的 URL 參數。如果提供字典或元組列表 [(key, value)],將會進行表單編碼。

  • auth – 授權處理常式或 (使用者, 密碼) 元組。

  • cookies – 要附加到此請求的 Cookie 字典或 CookieJar。

  • hooks – 回呼 Hook 字典,用於內部使用。

用法

>>> import requests
>>> req = requests.Request('GET', 'https://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
deregister_hook(event, hook)

取消註冊先前註冊的 Hook。如果 Hook 存在則傳回 True,否則傳回 False。

prepare()[source]

建構用於傳輸的 PreparedRequest 並傳回它。

register_hook(event, hook)

正確註冊 Hook。

class requests.Response[source]

Response 物件,其中包含伺服器對 HTTP 請求的回應。

property apparent_encoding

由 charset_normalizer 或 chardet 程式庫提供的明顯編碼。

close()[source]

將連線釋放回連線池。一旦呼叫此方法,就不得再次存取底層 raw 物件。

注意:通常不需要明確呼叫。

property content

回應的內容,以位元組為單位。

cookies

伺服器傳回的 CookieJar。

elapsed

發送請求與收到回應之間經過的時間量(以 timedelta 表示)。此屬性專門測量發送請求的第一個位元組和完成剖析標頭之間所花費的時間。因此,它不受取用回應內容或 stream 關鍵字引數值影響。

encoding

存取 r.text 時要使用的解碼編碼。

headers

不區分大小寫的回應標頭字典。例如,headers['content-encoding'] 將傳回 'Content-Encoding' 回應標頭的值。

history

來自 Request 歷史記錄的 Response 物件列表。任何重新導向回應都將在此處結束。列表從最舊的請求到最新的請求排序。

property is_permanent_redirect

如果此 Response 是永久重新導向版本之一,則為 True。

property is_redirect

如果此 Response 是格式正確的 HTTP 重新導向,可以自動處理(透過 Session.resolve_redirects),則為 True。

iter_content(chunk_size=1, decode_unicode=False)[source]

迭代回應資料。當請求上設定 stream=True 時,這可以避免一次將大型回應的內容讀取到記憶體中。chunk size 是應讀取到記憶體中的位元組數。這不一定是傳回的每個項目的長度,因為可能會發生解碼。

chunk_size 必須是 int 或 None 類型。None 值的功能會根據 stream 的值而有所不同。stream=True 將在資料到達時,以接收到的任何區塊大小讀取資料。如果 stream=False,資料將以單個區塊傳回。

如果 decode_unicode 為 True,則將使用基於回應的最佳可用編碼來解碼內容。

iter_lines(chunk_size=512, decode_unicode=False, delimiter=None)[source]

一次迭代一行回應資料。當請求上設定 stream=True 時,這可以避免一次將大型回應的內容讀取到記憶體中。

注意

此方法不是可重入安全的。

json(**kwargs)[source]

傳回回應的 JSON 編碼內容(如果有的話)。

參數:

**kwargsjson.loads 接受的選填引數。

Raises:

requests.exceptions.JSONDecodeError – 如果回應主體不包含有效的 JSON。

傳回回應的剖析標頭連結(如果有的話)。

property next

如果存在重新導向鏈中的下一個請求,則傳回該請求的 PreparedRequest。

property ok

如果 status_code 小於 400 則傳回 True,否則傳回 False。

此屬性檢查回應的狀態碼是否在 400 到 600 之間,以查看是否存在用戶端錯誤或伺服器錯誤。如果狀態碼在 200 到 400 之間,則會傳回 True。這不是檢查回應碼是否為 200 OK

raise_for_status()[source]

如果發生錯誤,則引發 HTTPError

raw

回應的類檔案物件表示形式(用於進階使用)。使用 raw 需要在請求上設定 stream=True。此要求不適用於 Requests 內部使用。

reason

回應 HTTP 狀態的文字原因,例如 “Not Found” 或 “OK”。

request

此回應所對應的 PreparedRequest 物件。

status_code

回應 HTTP 狀態的整數代碼,例如 404 或 200。

property text

回應的內容,以 Unicode 表示。

如果 Response.encoding 為 None,則將使用 charset_normalizerchardet 猜測編碼。

回應內容的編碼完全根據 HTTP 標頭確定,並遵循 RFC 2616 的規定。如果您可以利用非 HTTP 知識來更好地猜測編碼,則應在存取此屬性之前適當地設定 r.encoding

url

Response 的最終 URL 位置。

更低層級的類別

class requests.PreparedRequest[source]

完全可變的 PreparedRequest 物件,其中包含將發送到伺服器的確切位元組。

實例是從 Request 物件產生的,不應手動實例化;這樣做可能會產生不良影響。

用法

>>> import requests
>>> req = requests.Request('GET', 'https://httpbin.org/get')
>>> r = req.prepare()
>>> r
<PreparedRequest [GET]>

>>> s = requests.Session()
>>> s.send(r)
<Response [200]>
body

要發送到伺服器的請求主體。

deregister_hook(event, hook)

取消註冊先前註冊的 Hook。如果 Hook 存在則傳回 True,否則傳回 False。

headers

HTTP 標頭字典。

hooks

回呼 Hook 字典,用於內部使用。

method

要發送到伺服器的 HTTP 動詞。

property path_url

建構要使用的路徑 URL。

prepare(method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None)[source]

使用給定的參數準備整個請求。

prepare_auth(auth, url='')[source]

準備給定的 HTTP 授權資料。

prepare_body(data, files, json=None)[source]

準備給定的 HTTP 主體資料。

prepare_content_length(body)[source]

根據請求方法和主體準備 Content-Length 標頭

prepare_cookies(cookies)[source]

準備給定的 HTTP Cookie 資料。

此函數最終使用 cookielib 從給定的 Cookie 產生 Cookie 標頭。由於 cookielib 的設計,如果標頭已存在,則不會重新產生標頭,這表示此函數對於 PreparedRequest 物件的生命週期只能呼叫一次。任何後續對 prepare_cookies 的呼叫都不會產生實際效果,除非事先移除 “Cookie” 標頭。

prepare_headers(headers)[source]

準備給定的 HTTP 標頭。

prepare_hooks(hooks)[source]

準備給定的 Hook。

prepare_method(method)[source]

準備給定的 HTTP 方法。

prepare_url(url, params)[source]

準備給定的 HTTP URL。

register_hook(event, hook)

正確註冊 Hook。

url

要將請求發送到的 HTTP URL。

class requests.adapters.BaseAdapter[source]

基礎傳輸适配器

close()[source]

清除适配器特定項目。

send(request, stream=False, timeout=None, verify=True, cert=None, proxies=None)[source]

發送 PreparedRequest 物件。傳回 Response 物件。

參數:
  • request – 正在發送的 PreparedRequest

  • stream – (選填) 是否串流請求內容。

  • timeout (floattuple) – (選填) 在放棄之前,等待伺服器發送資料的最長時間,以浮點數或 (連線逾時, 讀取逾時) 元組表示。

  • verify – (選填) 布林值或字串。如果是布林值,則控制是否驗證伺服器的 TLS 憑證;如果是字串,則必須是 CA 捆綁包的路徑以供使用

  • cert – (選填) 任何使用者提供的要信任的 SSL 憑證。

  • proxies – (選填) 要應用於請求的代理字典。

class requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10, max_retries=0, pool_block=False)[source]

urllib3 的內建 HTTP 适配器。

透過實作傳輸适配器介面,為 Requests sessions 提供聯絡 HTTP 和 HTTPS URL 的通用介面。此類別通常由底層的 Session 類別建立。

參數:
  • pool_connections – 要快取的 urllib3 連線池數量。

  • pool_maxsize – 池中要儲存的最大連線數。

  • max_retries – 每個連線嘗試的最大重試次數。請注意,這僅適用於失敗的 DNS 查詢、Socket 連線和連線逾時,絕不適用於已將資料傳送到伺服器的請求。預設情況下,Requests 不會重試失敗的連線。如果您需要精細控制我們重試請求的條件,請導入 urllib3 的 Retry 類別並改為傳遞它。

  • pool_block – 連線池是否應封鎖連線。

用法

>>> import requests
>>> s = requests.Session()
>>> a = requests.adapters.HTTPAdapter(max_retries=3)
>>> s.mount('http://', a)
add_headers(request, **kwargs)[source]

新增連線所需的任何標頭。從 v2.0 開始,預設情況下此方法不會執行任何操作,但保留給子類別化 HTTPAdapter 的使用者覆寫。

不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:
  • request – 要新增標頭的 PreparedRequest

  • kwargs – 從 send() 呼叫傳遞的關鍵字引數。

build_connection_pool_key_attributes(request, verify, cert=None)[source]

建立 urllib3 用於傳回連線的 PoolKey 屬性。

此方法會查看 PreparedRequest、使用者指定的驗證值以及 cert 參數的值,以判斷要使用哪些 PoolKey 值從給定的 urllib3 連線池中選取連線。

SSL 相關的池金鑰引數未一致地設定。截至撰寫本文時,請使用以下方法來判斷該字典中可能有哪些金鑰

  • 如果 verifyTrue,則會設定 "ssl_context",並且會是預設的 Requests SSL Context

  • 如果 verifyFalse,則不會設定 "ssl_context",但會設定 "cert_reqs"

  • 如果 verify 是字串 (即,它是使用者指定的信任憑證包),如果該字串不是 os.path.isdir 辨識的目錄,則會設定 "ca_certs",否則會設定 "ca_certs_dir"

  • 如果指定 "cert",則始終會設定 "cert_file"。如果 "cert" 是包含第二個項目的元組,則也會存在 "key_file"

若要覆寫這些設定,可以將此類別子類別化,呼叫此方法並使用上述邏輯來變更所需的參數。例如,如果想要使用自訂的 ssl.SSLContext,則必須同時設定 "ssl_context",並根據他們要求的其他內容,變更其他金鑰以確保所需的行為。

參數:
  • request (PreparedRequest) – 透過連線傳送的 PreparedReqest。

  • verify – 布林值,在此情況下,它控制我們是否驗證伺服器的 TLS 憑證;或者字串,在此情況下,它必須是要使用的 CA 憑證包的路徑。

  • cert – (選用) 任何使用者提供的 SSL 憑證,用於用戶端驗證 (又稱 mTLS)。這可以是字串 (即,僅包含憑證和金鑰的檔案路徑) 或長度為 2 的元組,包含憑證檔案路徑和金鑰檔案路徑。

回傳值:

包含兩個字典的元組。第一個是 Pool Key 的「主機參數」部分,包括 scheme、hostname 和 port。第二個是 SSLContext 相關參數的字典。

build_response(req, resp)[source]

從 urllib3 回應建立 Response 物件。不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用

參數:
  • req – 用於產生回應的 PreparedRequest

  • resp – urllib3 回應物件。

回傳類型:

requests.Response

cert_verify(conn, url, verify, cert)[source]

驗證 SSL 憑證。不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:
  • conn – 與憑證關聯的 urllib3 連線物件。

  • url – 請求的 URL。

  • verify – 布林值,在此情況下,它控制我們是否驗證伺服器的 TLS 憑證;或者字串,在此情況下,它必須是要使用的 CA 憑證包的路徑

  • cert – 要驗證的 SSL 憑證。

close()[source]

處置任何內部狀態。

目前,這會關閉 PoolManager 和任何作用中的 ProxyManager,進而關閉任何池化的連線。

get_connection(url, proxies=None)[source]

已棄用:對於使用 Requests>=2.32.2 的 HTTPAdapter 所有子類別,使用者應改用 get_connection_with_tls_context

傳回給定 URL 的 urllib3 連線。不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:
  • url – 要連線的 URL。

  • proxies – (選用) 此請求上使用的 Requests 樣式 Proxy 字典。

回傳類型:

urllib3.ConnectionPool

get_connection_with_tls_context(request, verify, proxies=None, cert=None)[source]

傳回給定請求和 TLS 設定的 urllib3 連線。不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:
  • request – 要透過連線傳送的 PreparedRequest 物件。

  • verify – 布林值,在此情況下,它控制我們是否驗證伺服器的 TLS 憑證;或者字串,在此情況下,它必須是要使用的 CA 憑證包的路徑。

  • proxies – (選填) 要應用於請求的代理字典。

  • cert – (選用) 任何使用者提供的 SSL 憑證,用於用戶端驗證 (又稱 mTLS)。

回傳類型:

urllib3.ConnectionPool

init_poolmanager(connections, maxsize, block=False, **pool_kwargs)[source]

初始化 urllib3 PoolManager。

不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:
  • connections – 要快取的 urllib3 連線池數量。

  • maxsize – 池中要儲存的最大連線數。

  • block – 在沒有可用連線時封鎖。

  • pool_kwargs – 用於初始化 Pool Manager 的額外關鍵字引數。

proxy_headers(proxy)[source]

傳回要新增至透過 Proxy 傳送之任何請求的標頭字典。這與 urllib3 Magic 搭配使用,以確保它們已正確傳送到 Proxy,而不是在使用 CONNECT 時傳送到通道請求中。

不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:

proxy – 用於此請求的 Proxy URL。

回傳類型:

dict

proxy_manager_for(proxy, **proxy_kwargs)[source]

傳回給定 Proxy 的 urllib3 ProxyManager。

不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:
  • proxy – 要傳回 urllib3 ProxyManager 的 Proxy。

  • proxy_kwargs – 用於組態 Proxy Manager 的額外關鍵字引數。

回傳值:

ProxyManager

回傳類型:

urllib3.ProxyManager

request_url(request, proxies)[source]

取得在發出最終請求時要使用的 URL。

如果訊息是透過 HTTP Proxy 傳送,則必須使用完整 URL。否則,我們應該只使用 URL 的路徑部分。

不應從使用者程式碼呼叫此方法,僅在子類別化 HTTPAdapter 時公開使用。

參數:
  • request – 正在發送的 PreparedRequest

  • proxies – 方案或方案和主機的字典,用於 Proxy URL。

回傳類型:

str

send(request, stream=False, timeout=None, verify=True, cert=None, proxies=None)[source]

發送 PreparedRequest 物件。傳回 Response 物件。

參數:
  • request – 正在發送的 PreparedRequest

  • stream – (選填) 是否串流請求內容。

  • timeout (floattupleurllib3 Timeout 物件) – (選用) 在放棄之前,等待伺服器傳送資料的最長時間,以浮點數或 (連線逾時, 讀取逾時) 元組表示。

  • verify – (選填) 布林值或字串。如果是布林值,則控制是否驗證伺服器的 TLS 憑證;如果是字串,則必須是 CA 捆綁包的路徑以供使用

  • cert – (選填) 任何使用者提供的要信任的 SSL 憑證。

  • proxies – (選填) 要應用於請求的代理字典。

回傳類型:

requests.Response

驗證

class requests.auth.AuthBase[source]

所有驗證實作衍生自的基底類別

class requests.auth.HTTPBasicAuth(username, password)[source]

將 HTTP 基本驗證附加到給定的 Request 物件。

class requests.auth.HTTPProxyAuth(username, password)[source]

將 HTTP Proxy 驗證附加到給定的 Request 物件。

class requests.auth.HTTPDigestAuth(username, password)[source]

將 HTTP 摘要式驗證附加到給定的 Request 物件。

編碼

requests.utils.get_encodings_from_content(content)[source]

從給定的內容字串傳回編碼。

參數:

content – 要從中擷取編碼的位元組字串。

requests.utils.get_encoding_from_headers(headers)[source]

從給定的 HTTP 標頭字典傳回編碼。

參數:

headers – 要從中擷取編碼的字典。

回傳類型:

str

requests.utils.get_unicode_from_response(r)[source]

以 Unicode 傳回請求的內容。

參數:

r – 要從中取得 Unicode 內容的回應物件。

嘗試過

  1. 來自 content-type 的 charset

  2. 回退並取代所有 Unicode 字元

回傳類型:

str

Cookie

requests.utils.dict_from_cookiejar(cj)[source]

從 CookieJar 傳回鍵/值字典。

參數:

cj – 要從中擷取 Cookie 的 CookieJar 物件。

回傳類型:

dict

requests.utils.add_dict_to_cookiejar(cj, cookie_dict)[source]

從鍵/值字典傳回 CookieJar。

參數:
  • cj – 要將 Cookie 插入其中的 CookieJar。

  • cookie_dict – 要插入 CookieJar 的鍵/值字典。

回傳類型:

CookieJar

requests.cookies.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)[source]

從鍵/值字典傳回 CookieJar。

參數:
  • cookie_dict – 要插入 CookieJar 的鍵/值字典。

  • cookiejar – (選用) 要將 Cookie 新增至其中的 CookieJar。

  • overwrite – (選用) 如果為 False,則不會將 Jar 中已有的 Cookie 替換為新的 Cookie。

回傳類型:

CookieJar

class requests.cookies.RequestsCookieJar(policy=None)[source]

相容性類別;是 http.cookiejar.CookieJar,但公開字典介面。

這是我們為未指定 CookieJar 的請求和工作階段預設建立的 CookieJar,因為某些用戶端可能期望 response.cookies 和 session.cookies 支援字典操作。

Requests 在內部未使用字典介面;它僅用於與外部用戶端程式碼相容。所有 Requests 程式碼都應與外部提供的 CookieJar 實例 (例如 LWPCookieJarFileCookieJar) 開箱即用。

與一般 CookieJar 不同,此類別可進行 pickle 序列化。

警告

通常為 O(1) 的字典操作可能為 O(n)。

將正確的 Cookie: 標頭新增至請求 (urllib.request.Request 物件)。

除非 policy.hide_cookie2 為 true,否則也會新增 Cookie2 標頭。

clear(domain=None, path=None, name=None)

清除一些 Cookie。

在不使用引數的情況下叫用此方法將清除所有 Cookie。如果給定單個引數,則只會移除屬於該網域的 Cookie。如果給定兩個引數,則會移除屬於該網域內指定路徑的 Cookie。如果給定三個引數,則會移除具有指定名稱、路徑和網域的 Cookie。

如果沒有相符的 Cookie,則會引發 KeyError。

clear_expired_cookies()

捨棄所有過期的 Cookie。

您可能不需要呼叫此方法:過期的 Cookie 永遠不會傳送回伺服器 (前提是您使用的是 DefaultCookiePolicy),此方法會由 CookieJar 本身每隔一段時間呼叫一次,並且 .save() 方法無論如何都不會儲存過期的 Cookie (除非您透過傳遞 true ignore_expires 引數來另行要求)。

clear_session_cookies()

捨棄所有工作階段 Cookie。

請注意,.save() 方法無論如何都不會儲存工作階段 Cookie,除非您透過傳遞 true ignore_discard 引數來另行要求。

copy()[source]

傳回此 RequestsCookieJar 的副本。

extract_cookies(response, request)

從回應中擷取 Cookie,在請求允許的情況下。

get(name, default=None, domain=None, path=None)[source]

類似字典的 get(),也支援選用的網域和路徑引數,以便解決從多個網域使用一個 Cookie Jar 造成的命名衝突。

警告

操作為 O(n),而非 O(1)。

get_dict(domain=None, path=None)[source]

將選用的網域和路徑作為引數,並傳回純 Python 字典,其中包含符合需求的 Cookie 的名稱-值組。

回傳類型:

dict

get_policy()[source]

傳回使用的 CookiePolicy 實例。

items()[source]

類似字典的 items(),傳回 Jar 中的名稱-值組清單。允許用戶端程式碼呼叫 dict(RequestsCookieJar) 並取得 vanilla python 鍵值組字典。

另請參閱

keys() 和 values()。

iteritems()[source]

類似字典的 iteritems(),傳回 Jar 中的名稱-值組迭代器。

另請參閱

iterkeys() 和 itervalues()。

iterkeys()[source]

類似字典的 iterkeys(),傳回 Jar 中的 Cookie 名稱迭代器。

另請參閱

itervalues() 和 iteritems()。

itervalues()[source]

Dict-like itervalues() that returns an iterator of values of cookies from the jar.

另請參閱

iterkeys() and iteritems().

keys()[source]

Dict-like keys() that returns a list of names of cookies from the jar.

另請參閱

values() and items().

list_domains()[source]

Utility method to list all the domains in the jar.

list_paths()[source]

Utility method to list all the paths in the jar.

make_cookies(response, request)

Return sequence of Cookie objects extracted from response object.

multiple_domains()[source]

Returns True if there are multiple domains in the jar. Returns False otherwise.

回傳類型:

bool

pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

set(name, value, **kwargs)[source]

Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.

Set a cookie, without checking whether or not it should be set.

Set a cookie if policy says it’s OK to do so.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update(other)[source]

Updates this jar with cookies from another CookieJar or dict-like

values()[source]

Dict-like values() that returns a list of values of cookies from the jar.

另請參閱

keys() and items().

class requests.cookies.CookieConflictError[source]

There are two cookies that meet the criteria specified in the cookie jar. Use .get and .set and include domain and path args in order to be more specific.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Status Code Lookup

requests.codes

alias of {}

The codes object defines a mapping from common names for HTTP statuses to their numerical codes, accessible either as attributes or as dictionary items.

Example

>>> import requests
>>> requests.codes['temporary_redirect']
307
>>> requests.codes.teapot
418
>>> requests.codes['\o/']
200

Some codes have multiple names, and both upper- and lower-case versions of the names are allowed. For example, codes.ok, codes.OK, and codes.okay all correspond to the HTTP status code 200.

  • 100: continue

  • 101: switching_protocols

  • 102: processing, early-hints

  • 103: checkpoint

  • 122: uri_too_long, request_uri_too_long

  • 200: ok, okay, all_ok, all_okay, all_good, \o/,

  • 201: created

  • 202: accepted

  • 203: non_authoritative_info, non_authoritative_information

  • 204: no_content

  • 205: reset_content, reset

  • 206: partial_content, partial

  • 207: multi_status, multiple_status, multi_stati, multiple_stati

  • 208: already_reported

  • 226: im_used

  • 300: multiple_choices

  • 301: moved_permanently, moved, \o-

  • 302: found

  • 303: see_other, other

  • 304: not_modified

  • 305: use_proxy

  • 306: switch_proxy

  • 307: temporary_redirect, temporary_moved, temporary

  • 308: permanent_redirect, resume_incomplete, resume

  • 400: bad_request, bad

  • 401: unauthorized

  • 402: payment_required, payment

  • 403: forbidden

  • 404: not_found, -o-

  • 405: method_not_allowed, not_allowed

  • 406: not_acceptable

  • 407: proxy_authentication_required, proxy_auth, proxy_authentication

  • 408: request_timeout, timeout

  • 409: conflict

  • 410: gone

  • 411: length_required

  • 412: precondition_failed, precondition

  • 413: request_entity_too_large, content_too_large

  • 414: request_uri_too_large, uri_too_long

  • 415: unsupported_media_type, unsupported_media, media_type

  • 416: requested_range_not_satisfiable, requested_range, range_not_satisfiable

  • 417: expectation_failed

  • 418: im_a_teapot, teapot, i_am_a_teapot

  • 421: misdirected_request

  • 422: unprocessable_entity, unprocessable, unprocessable_content

  • 423: locked

  • 424: failed_dependency, dependency

  • 425: unordered_collection, unordered, too_early

  • 426: upgrade_required, upgrade

  • 428: precondition_required, precondition

  • 429: too_many_requests, too_many

  • 431: header_fields_too_large, fields_too_large

  • 444: no_response, none

  • 449: retry_with, retry

  • 450: blocked_by_windows_parental_controls, parental_controls

  • 451: unavailable_for_legal_reasons, legal_reasons

  • 499: client_closed_request

  • 500: internal_server_error, server_error, /o\,

  • 501: not_implemented

  • 502: bad_gateway

  • 503: service_unavailable, unavailable

  • 504: gateway_timeout

  • 505: http_version_not_supported, http_version

  • 506: variant_also_negotiates

  • 507: insufficient_storage

  • 509: bandwidth_limit_exceeded, bandwidth

  • 510: not_extended

  • 511: network_authentication_required, network_auth, network_authentication

Migrating to 1.x

This section details the main differences between 0.x and 1.x and is meant to ease the pain of upgrading.

API Changes

  • Response.json is now a callable and not a property of a response.

    import requests
    r = requests.get('https://api.github.com/events')
    r.json()   # This *call* raises an exception if JSON decoding fails
    
  • The Session API has changed. Sessions objects no longer take parameters. Session is also now capitalized, but it can still be instantiated with a lowercase session for backwards compatibility.

    s = requests.Session()    # formerly, session took parameters
    s.auth = auth
    s.headers.update(headers)
    r = s.get('https://httpbin.org/headers')
    
  • All request hooks have been removed except ‘response’.

  • Authentication helpers have been broken out into separate modules. See requests-oauthlib and requests-kerberos.

  • The parameter for streaming requests was changed from prefetch to stream and the logic was inverted. In addition, stream is now required for raw response reading.

    # in 0.x, passing prefetch=False would accomplish the same thing
    r = requests.get('https://api.github.com/events', stream=True)
    for chunk in r.iter_content(8192):
        ...
    
  • The config parameter to the requests method has been removed. Some of these options are now configured on a Session such as keep-alive and maximum number of redirects. The verbosity option should be handled by configuring logging.

    import requests
    import logging
    
    # Enabling debugging at http.client level (requests->urllib3->http.client)
    # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
    # the only thing missing will be the response.body which is not logged.
    try: # for Python 3
        from http.client import HTTPConnection
    except ImportError:
        from httplib import HTTPConnection
    HTTPConnection.debuglevel = 1
    
    logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
    logging.getLogger().setLevel(logging.DEBUG)
    requests_log = logging.getLogger("urllib3")
    requests_log.setLevel(logging.DEBUG)
    requests_log.propagate = True
    
    requests.get('https://httpbin.org/headers')
    

Licensing

One key difference that has nothing to do with the API is a change in the license from the ISC license to the Apache 2.0 license. The Apache 2.0 license ensures that contributions to Requests are also covered by the Apache 2.0 license.

Migrating to 2.x

Compared with the 1.0 release, there were relatively few backwards incompatible changes, but there are still a few issues to be aware of with this major release.

For more details on the changes in this release including new APIs, links to the relevant GitHub issues and some of the bug fixes, read Cory’s blog on the subject.

API Changes

  • There were a couple changes to how Requests handles exceptions. RequestException is now a subclass of IOError rather than RuntimeError as that more accurately categorizes the type of error. In addition, an invalid URL escape sequence now raises a subclass of RequestException rather than a ValueError.

    requests.get('http://%zz/')   # raises requests.exceptions.InvalidURL
    

    Lastly, httplib.IncompleteRead exceptions caused by incorrect chunked encoding will now raise a Requests ChunkedEncodingError instead.

  • The proxy API has changed slightly. The scheme for a proxy URL is now required.

    proxies = {
      "http": "10.10.1.10:3128",    # use http://10.10.1.10:3128 instead
    }
    
    # In requests 1.x, this was legal, in requests 2.x,
    #  this raises requests.exceptions.MissingSchema
    requests.get("http://example.org", proxies=proxies)
    

Behavioural Changes

  • Keys in the headers dictionary are now native strings on all Python versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the keys are not native strings (unicode on Python 2 or bytestrings on Python 3) they will be converted to the native string type assuming UTF-8 encoding.

  • Values in the headers dictionary should always be strings. This has been the project’s position since before 1.0 but a recent change (since version 2.11.0) enforces this more strictly. It’s advised to avoid passing header values as unicode when possible.