開發者介面¶
此文件部分涵蓋 Requests 的所有介面。對於 Requests 依賴外部函式庫的部分,我們在此記錄最重要的內容,並提供連到標準文件的連結。
主要介面¶
Requests 的所有功能都可以透過這 7 種方法存取。它們都會回傳 Response
物件的實例。
- requests.request(method, url, **kwargs)[原始碼]¶
建構並發送
Request
。- 參數:
method – 新
Request
物件的方法:GET
、OPTIONS
、HEAD
、POST
、PUT
、PATCH
或DELETE
。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 (float 或 tuple) – (選填) 等待伺服器發送資料的最長秒數,以 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
物件- 回傳類型:
用法
>>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') >>> req <Response [200]>
例外¶
- exception requests.Timeout(*args, **kwargs)[原始碼]¶
請求逾時。
捕捉此錯誤將同時捕捉
ConnectTimeout
和ReadTimeout
錯誤。
請求 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]>
- cert¶
SSL 用戶端憑證預設值。如果是字串,則為 SSL 用戶端憑證檔案 (.pem) 的路徑。如果是元組,則為 ('cert', 'key') 對。
- cookies¶
一個 CookieJar,包含此 session 上目前所有未過期的 Cookie。預設情況下,它是一個
RequestsCookieJar
,但也可能是任何其他相容於cookielib.CookieJar
的物件。
- delete(url, **kwargs)[原始碼]¶
發送 DELETE 請求。回傳
Response
物件。- 參數:
url – 新
Request
物件的 URL。**kwargs –
request
接受的選填引數。
- 回傳類型:
- get(url, **kwargs)[原始碼]¶
發送 GET 請求。回傳
Response
物件。- 參數:
url – 新
Request
物件的 URL。**kwargs –
request
接受的選填引數。
- 回傳類型:
- get_redirect_target(resp)¶
接收 Response。回傳重新導向 URI 或
None
- head(url, **kwargs)[原始碼]¶
發送 HEAD 請求。回傳
Response
物件。- 參數:
url – 新
Request
物件的 URL。**kwargs –
request
接受的選填引數。
- 回傳類型:
- hooks¶
事件處理 hook。
- max_redirects¶
允許的最大重新導向次數。如果請求超過此限制,則會引發
TooManyRedirects
例外。預設值為 requests.models.DEFAULT_REDIRECT_LIMIT,即 30。
- options(url, **kwargs)[原始碼]¶
發送 OPTIONS 請求。回傳
Response
物件。- 參數:
url – 新
Request
物件的 URL。**kwargs –
request
接受的選填引數。
- 回傳類型:
- prepare_request(request)[原始碼]¶
建構用於傳輸的
PreparedRequest
並回傳它。PreparedRequest
具有從Request
實例和Session
的設定合併而來的設定。- 參數:
request – 要使用此 session 的設定準備的
Request
實例。- 回傳類型:
- proxies¶
將協定或協定和主機對應到 Proxy URL 的字典 (例如 {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}),將用於每個
Request
。
- rebuild_auth(prepared_request, response)¶
當重新導向時,我們可能希望從請求中移除驗證,以避免洩漏憑證。此方法會智慧地移除並重新應用驗證 (如果可能),以避免憑證遺失。
- rebuild_method(prepared_request, response)¶
當重新導向時,我們可能希望根據某些規範或瀏覽器行為來變更請求的方法。
- rebuild_proxies(prepared_request, proxies)¶
此方法透過考量環境變數來重新評估 Proxy 組態。如果我們重新導向到 NO_PROXY 涵蓋的 URL,我們會移除 Proxy 組態。否則,我們會為此 URL 設定遺失的 Proxy 金鑰 (以防它們被先前的重新導向移除)。
此方法也會在必要時替換 Proxy-Authorization 標頭。
- 回傳類型:
- 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 (float 或 tuple) – (選填) 在放棄之前,等待伺服器發送資料的最長時間,以浮點數或 (連線逾時, 讀取逾時) 元組表示。
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') 對。
- 回傳類型:
- resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)¶
接收 Response。傳回 Responses 或 Requests 的產生器。
- 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 程式庫提供的明顯編碼。
- property content¶
回應的內容,以位元組為單位。
- cookies¶
伺服器傳回的 CookieJar。
- elapsed¶
發送請求與收到回應之間經過的時間量(以 timedelta 表示)。此屬性專門測量發送請求的第一個位元組和完成剖析標頭之間所花費的時間。因此,它不受取用回應內容或
stream
關鍵字引數值影響。
- encoding¶
存取 r.text 時要使用的解碼編碼。
- headers¶
不區分大小寫的回應標頭字典。例如,
headers['content-encoding']
將傳回'Content-Encoding'
回應標頭的值。
- 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 編碼內容(如果有的話)。
- 參數:
**kwargs –
json.loads
接受的選填引數。- Raises:
requests.exceptions.JSONDecodeError – 如果回應主體不包含有效的 JSON。
- property links¶
傳回回應的剖析標頭連結(如果有的話)。
- property next¶
如果存在重新導向鏈中的下一個請求,則傳回該請求的 PreparedRequest。
- property ok¶
如果
status_code
小於 400 則傳回 True,否則傳回 False。此屬性檢查回應的狀態碼是否在 400 到 600 之間,以查看是否存在用戶端錯誤或伺服器錯誤。如果狀態碼在 200 到 400 之間,則會傳回 True。這不是檢查回應碼是否為
200 OK
。
- raw¶
回應的類檔案物件表示形式(用於進階使用)。使用
raw
需要在請求上設定stream=True
。此要求不適用於 Requests 內部使用。
- reason¶
回應 HTTP 狀態的文字原因,例如 “Not Found” 或 “OK”。
- request¶
此回應所對應的
PreparedRequest
物件。
- status_code¶
回應 HTTP 狀態的整數代碼,例如 404 或 200。
- property text¶
回應的內容,以 Unicode 表示。
如果 Response.encoding 為 None,則將使用
charset_normalizer
或chardet
猜測編碼。回應內容的編碼完全根據 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_cookies(cookies)[source]¶
準備給定的 HTTP Cookie 資料。
此函數最終使用 cookielib 從給定的 Cookie 產生
Cookie
標頭。由於 cookielib 的設計,如果標頭已存在,則不會重新產生標頭,這表示此函數對於PreparedRequest
物件的生命週期只能呼叫一次。任何後續對prepare_cookies
的呼叫都不會產生實際效果,除非事先移除 “Cookie” 標頭。
- register_hook(event, hook)¶
正確註冊 Hook。
- url¶
要將請求發送到的 HTTP URL。
- class requests.adapters.BaseAdapter[source]¶
基礎傳輸适配器
- send(request, stream=False, timeout=None, verify=True, cert=None, proxies=None)[source]¶
發送 PreparedRequest 物件。傳回 Response 物件。
- 參數:
request – 正在發送的
PreparedRequest
。stream – (選填) 是否串流請求內容。
timeout (float 或 tuple) – (選填) 在放棄之前,等待伺服器發送資料的最長時間,以浮點數或 (連線逾時, 讀取逾時) 元組表示。
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 相關的池金鑰引數未一致地設定。截至撰寫本文時,請使用以下方法來判斷該字典中可能有哪些金鑰
如果
verify
為True
,則會設定"ssl_context"
,並且會是預設的 Requests SSL Context如果
verify
為False
,則不會設定"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 回應物件。
- 回傳類型:
- cert_verify(conn, url, verify, cert)[source]¶
驗證 SSL 憑證。不應從使用者程式碼呼叫此方法,僅在子類別化
HTTPAdapter
時公開使用。- 參數:
conn – 與憑證關聯的 urllib3 連線物件。
url – 請求的 URL。
verify – 布林值,在此情況下,它控制我們是否驗證伺服器的 TLS 憑證;或者字串,在此情況下,它必須是要使用的 CA 憑證包的路徑
cert – 要驗證的 SSL 憑證。
- 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。
- 回傳類型:
- proxy_manager_for(proxy, **proxy_kwargs)[source]¶
傳回給定 Proxy 的 urllib3 ProxyManager。
不應從使用者程式碼呼叫此方法,僅在子類別化
HTTPAdapter
時公開使用。- 參數:
proxy – 要傳回 urllib3 ProxyManager 的 Proxy。
proxy_kwargs – 用於組態 Proxy Manager 的額外關鍵字引數。
- 回傳值:
ProxyManager
- 回傳類型:
- request_url(request, proxies)[source]¶
取得在發出最終請求時要使用的 URL。
如果訊息是透過 HTTP Proxy 傳送,則必須使用完整 URL。否則,我們應該只使用 URL 的路徑部分。
不應從使用者程式碼呼叫此方法,僅在子類別化
HTTPAdapter
時公開使用。- 參數:
request – 正在發送的
PreparedRequest
。proxies – 方案或方案和主機的字典,用於 Proxy URL。
- 回傳類型:
- send(request, stream=False, timeout=None, verify=True, cert=None, proxies=None)[source]¶
發送 PreparedRequest 物件。傳回 Response 物件。
- 參數:
request – 正在發送的
PreparedRequest
。stream – (選填) 是否串流請求內容。
timeout (float 或 tuple 或 urllib3 Timeout 物件) – (選用) 在放棄之前,等待伺服器傳送資料的最長時間,以浮點數或 (連線逾時, 讀取逾時) 元組表示。
verify – (選填) 布林值或字串。如果是布林值,則控制是否驗證伺服器的 TLS 憑證;如果是字串,則必須是 CA 捆綁包的路徑以供使用
cert – (選填) 任何使用者提供的要信任的 SSL 憑證。
proxies – (選填) 要應用於請求的代理字典。
- 回傳類型:
驗證¶
編碼¶
- requests.utils.get_encodings_from_content(content)[source]¶
從給定的內容字串傳回編碼。
- 參數:
content – 要從中擷取編碼的位元組字串。
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 lowercasesession
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
tostream
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 aSession
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 ofIOError
rather thanRuntimeError
as that more accurately categorizes the type of error. In addition, an invalid URL escape sequence now raises a subclass ofRequestException
rather than aValueError
.requests.get('http://%zz/') # raises requests.exceptions.InvalidURL
Lastly,
httplib.IncompleteRead
exceptions caused by incorrect chunked encoding will now raise a RequestsChunkedEncodingError
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.