本文介紹 Python Requests 庫的開發者接口,主要內容包括:
目錄
1. requests.request()
2. requests.head()、get()、post()、put()、patch()、delete()
1. requests.request(method, url, **kwargs)
構造並發送一個Request對象,返回一個Response對象。
參數:
- method – 新建 Request 對象要使用的HTTP方法
- url – 新建 Request 對象的URL
- params – (可選) Request 對象的查詢字符中要發送的字典或字節內容
- data – (可選) Request 對象的 body 中要包括的字典、字節或類文件數據
- json – (可選) Request 對象的 body 中要包括的 Json 數據
- headers – (可選) Request 對象的字典格式的 HTTP 頭
- cookies – (可選) Request 對象的字典或 CookieJar 對象
- files – (可選) 字典,'name': file-like-objects (或{'name': ('filename', fileobj)}) 用於上傳含多個部分的(類)文件對象
- auth – (可選) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
- timeout (浮點或元組) – (可選) 等待服務器數據的超時限制,是一個浮點數,或是一個(connect timeout, read timeout) 元組
- allow_redirects (bool) – (可選) Boolean. True 表示允許跟蹤 POST/PUT/DELETE 方法的重定向
- proxies – (可選) 字典,用於將協議映射為代理的URL
- verify – (可選) 為 True 時將會驗證 SSL 證書,也可以提供一個 CA_BUNDLE 路徑
- stream – (可選) 如果為 False,將會立即下載響應內容
- cert – (可選) 為字符串時應是 SSL 客戶端證書文件的路徑(.pem格式),如果是元組,就應該是一個(‘cert’, ‘key’) 二元值對
示例:
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>
2. requests.head(url, **kwargs)
發送一個 HEAD 請求,返回一個 Response 對象
參數:
- url – 新建 Request 對象的URL
- **kwargs – 見 request 方法接收的可選參數
3. requests.get(url, **kwargs)
發送一個 GET 請求,返回一個 Response 對象
參數:
- url – 新建 Request 對象的URL
- **kwargs – 見 request 方法接收的可選參數
4. requests.post(url, data=None, **kwargs)
發送一個 POST 請求,返回一個 Response 對象
參數:
- url – 新建 Request 對象的URL
- data – (可選) Request 對象的 body 中要包括的字典、字節或類文件數據
- **kwargs – 見 request 方法接收的可選參數
5. requests.put(url, data=None, **kwargs)
發送一個 PUT 請求,返回一個 Response 對象
參數:
- url – 新建 Request 對象的URL
- data – (可選) Request 對象的 body 中要包括的字典、字節或類文件數據
- **kwargs – 見 request 方法接收的可選參數
6. requests.patch(url, data=None, **kwargs)
發送一個 PUT 請求,返回一個 Response 對象
參數:
- url – 新建 Request 對象的URL
- data – (可選) Request 對象的 body 中要包括的字典、字節或類文件數據
- **kwargs – 見 request 方法接收的可選參數
7. requests.delete(url, **kwargs)
發送一個 PUT 請求,返回一個 Response 對象
參數:
- url – 新建 Request 對象的URL
- **kwargs – 見 request 方法接收的可選參數
exception requests.RequestException
處理你的請求時出現了一個有歧義的異常
exception requests.ConnectionError
連接異常
exception requests.HTTPError(*args, **kwargs)
HTTP 錯誤
exception requests.URLRequired
無效的請求 URL
exception requests.TooManyRedirects
重定向過多
exception requests.exceptions.ConnectTimeout(*args, **kwargs)
The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
exception requests.exceptions.ReadTimeout(*args, **kwargs)
The server did not send any data in the allotted amount of time.
exception requests.exceptions.Timeout(*args, **kwargs)
請求超時限制,Catching this error will catch both ConnectTimeout and ReadTimeout errors.
requests.Request(method=None, url=None, headers=None, files=None, data={}, params={}, auth=None, cookies=None, hooks=None)
由用戶創建的 Request 對象,用來准備一個 PreparedRequest 對象,后者被發給服務器
參數:
- method – 要使用的 HTTP 方法
- url – 目標 URL
- headers – 字典,要發送的 HTTP header
- files – 字典,形式為{filename: fileobject},表示要上傳的多個部分
- data – the body to attach the request. If a dictionary is provided, form-encoding will take place.
- params – 字典,包含追加到 URL 后的 URL 參數
- auth – Auth 句柄或 (user, pass) 元組
- cookies – 附加到這個請求的字典或 CookieJar 對象的cookies
- hooks – dictionary of callback hooks, for internal usage.
示例:
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
方法:
1. register_hook(event, hook)
注冊一個事件鈎子
2. deregister_hook(event, hook)
撤銷一個已經注冊的 hook,如果 hook 存在則返回 True,否則返回 False
3. prepare()
構造一個 PreparedRequest 對象用於傳輸,返回一個 PreparedRequest 對象
class requests.PreparedRequest
完全可變的 PreparedRequest 對象,包含將會發送給服務器的字節,由 Request 或手動創建
示例:
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> r = req.prepare()
<PreparedRequest [GET]>
>>> s = requests.Session()
>>> s.send(r)
<Response [200]>
屬性與方法:
1. body = None
發送給服務器的請求 body
2. deregister_hook(event, hook)
撤銷一個已經注冊的 hook,如果 hook 存在則返回 True,否則返回 False
3. headers = None
由HTTP headers構成的字典
4. hooks = None
dictionary of callback hooks, 僅供內部使用
5. method = None
HTTP 方法
6. path_url
構造要使用的路徑URL
7. prepare(method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None)
用給定的參數准備整個請求
8. prepare_auth(auth, url='')
准備給定的 HTTP 認證數據
9. prepare_body(data, files, json=None)
准備給定的 HTTP body 數據
10. prepare_cookies(cookies)
准備給定的 HTTP cookie 數據
11. prepare_headers(headers)
准備給定的 HTTP headers
12. prepare_hooks(hooks)
准備給定的 hooks
13. prepare_method(method)
准備給定的 HTTP 方法
14. prepare_url(url, params)
准備給定的 HTTP URL
15. register_hook(event, hook)
適當地注冊一個 hook
16. url = None
將請求發往的 HTTP URL
requests.Response
Response 對象,包含一個服務器對與 HTTP 請求的響應
屬性與方法:
1. apparent_encoding
The apparent encoding, provided by the lovely Charade library (Thanks, Ian!).
2. content
以字節表示的響應內容
3. cookies = None
一個服務器發回的 cookie 的 CookieJar
4. elapsed = None
發出請求和接收到響應之間的時間間隔 (一個 timedelta)
5. encoding = None
訪問r.text時要以何種編碼方式解碼
6. headers = None
大小寫無關的響應頭組成的字典,例如: headers['content-encoding'] 將會返回 'Content-Encoding' 響應頭的值
7. history = None
A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.
8. iter_content(chunk_size=1, decode_unicode=False)
Iterates over the response data. This avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
9. iter_lines(chunk_size=512, decode_unicode=None)
Iterates over the response data, one line at a time. This avoids reading the content at once into memory for large responses.
10. json(**kwargs)
如果存在,返回JSON格式編碼的響應內容
參數:
- **kwargs – json.loads接受的可選參數
11. links
Returns the parsed header links of the response, if any.
12. raise_for_status()
Raises stored HTTPError, if one occurred.
13. raw = None
File-like object representation of response (for advanced usage). Requires that ``stream=True` on the request.
14. status_code = None
Integer Code of responded HTTP Status.
15. text
uncode格式的響應內容
如果 Response.encoding 是 None 且 chardet 模塊可用,將會猜測響應的編碼格式
16. url = None
響應的最終URL地址
requests.Session
一個 Requests 會話對象,提供 cookie 的存儲,連接池和配置
示例:
>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
200
屬性與方法:
1. auth = None
附加到 Request 對象上的默認認證元組或對象
2. cert = None
SSL 證書的缺省值
3. close()
關閉所有的 adapters 和 session
4. delete(url, **kwargs)
發送一個 DELETE 請求,返回 Response 對象
參數:
- url – URL for the new Request object.
- **kwargs – 可選 arguments that request takes
5. get(url, **kwargs)
發送一個 GET 請求,返回 Response 對象
參數:
- url – URL for the new Request object.
- **kwargs – 可選 arguments that request takes.
6. get_adapter(url)
返回給定URL的適當連接適配器
7. head(url, **kwargs)
發送一個 HEAD 請求,返回 Response 對象
參數:
- url – 新 Request 對象的URL
- **kwargs – 請求需要的可選參數
8. headers = None
一個大小寫不敏感的字典,包含了這個 Session 發出的所有 Request 對象都包含的 headers
9. hooks = None
事件處理 hook
10. max_redirects = None
最大重定向次數
11. mount(prefix, adapter)
將一個連接適配器注冊到一個前綴上
12. options(url, **kwargs)
發送一個 OPTIONS 請求,返回 Response 對象
參數:
- url – URL for the new Request object.
- **kwargs – 可選 arguments that request takes.
13. params = None
Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.
14. patch(url, data=None, **kwargs)
發送一個 PATCH 請求,返回 Response 對象
參數:
- url – URL for the new Request object.
- data – (可選) Dictionary, bytes, or file-like object to send in the body of the Request.
- **kwargs – 可選 arguments that request takes.
15. post(url, data=None, **kwargs)
發送一個 POST 請求,返回 Response 對象
參數:
- url – URL for the new Request object.
- data – (可選) Dictionary, bytes, or file-like object to send in the body of the Request.
- **kwargs – 可選 arguments that request takes.
16. proxies = None
字典,將協議映射為每個Request使用的代理URL地址(例如: {‘http’: ‘foo.bar:3128’})
17. put(url, data=None, **kwargs)
發送一個 PUT 請求,返回 Response 對象
參數:
- url – 新 Request 對象的 URL
- data – (可選) Dictionary, bytes, or file-like object to send in the body of the Request.
- **kwargs – 可選 arguments that request takes.
18. resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None)
接受一個 Response,返回一個 Responses 的 generator
19. send(request, **kwargs)
發送一個給定的 PreparedRequest 對象
20. stream = None
流式響應內容
21. trust_env = None
是否信任環境
22. verify = None
SSL 驗證的默認值
class requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10, max_retries=0, pool_block=False)
針對 urllib3 的內置 HTTP Adapter,通過實現傳輸適配器接口,為 session 和 HTTP、 HTTPS連接提供了一個通用的接口。該類的實例通常由內部包裹下的Session類創建。
參數:
- pool_connections – 緩存的 urllib3 連接池個數
- pool_maxsize – 連接池中保存的最大連接數
- max_retries (int) – 每次連接的最大失敗重試次數,只用於 DNS 查詢失敗,socket 連接或連接超時,默認情況下 Requests 不會重試失敗的連接,如果你需要對請求重試的條件進行細粒度的控制,可以引入 urllib3 的 Retry 類
- pool_block – 連接池是否應該為連接阻塞
示例:
>>> import requests
>>> s = requests.Session()
>>> a = requests.adapters.HTTPAdapter(max_retries=3)
>>> s.mount('http://', a)
方法:
1. add_headers(request, **kwargs)
添加需要的 header,用戶代碼中不應該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
- request – 要添加 header 的 PreparedRequest 對象
- kwargs – 同於調用 send() 時的關鍵字參數
2. build_response(req, resp)
從一個 urllib3 響應構建一個Response對象,用戶代碼中不該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
- req – 用於產生響應的 PreparedRequest 對象
- resp – urllib3 響應對象
3. cert_verify(conn, url, verify, cert)
驗證一個 SSL 證書,用戶代碼中不該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
- conn – 與證書相關的 urllib3 connection 對象
- url – 被請求的 URL.
- verify – 是否真的驗證證書
- cert – 要驗證的 SSL 證書
4. close()
處理掉所有的內部狀態
當前該方法僅僅關閉 PoolManager 進而斷開池中的連接
5. get_connection(url, proxies=None)
對於給定的URL,返回一個 urllib3 連接。 用戶代碼中不該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
url – 要連接的URL
proxies – (可選) 一個 Requests 風格的字典,內容是此次請求使用的代理
6. init_poolmanager(connections, maxsize, block=False, **pool_kwargs)
初始化一個 urllib3 PoolManager 實例
用戶代碼中不該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
- connections – 要緩存的 urllib3 連接池的個數
- maxsize – 連接池可容納的最大連接數
- block – 沒有可用連接時就阻塞
- pool_kwargs – 初始化 Pool Manager 的其他關鍵字參數
7. proxy_headers(proxy)
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used.
用戶代碼中不該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
- proxies – 該請求使用的代理URL
- kwargs – 可選的關鍵字參數
8. proxy_manager_for(proxy, **proxy_kwargs)
返回給定代理的 urllib3 ProxyManager 對象,用戶代碼中不該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
- proxy – 要返回 urllib3 ProxyManager 的代理
- proxy_kwargs – 用來配置Proxy Manager 的額外的關鍵字參數
返回:
ProxyManager
9. request_url(request, proxies)
獲取最后一個請求的url,如果消息是由HTTP代理發送的,則必須使用完整的URL,否則只需要使用URL的路徑部分
用戶代碼中不該調用該方法,該方法應該只在 HTTPAdapter 的子類中使用
參數:
- request – 要發送的 PreparedRequest 對象
- proxies – A dictionary of schemes to proxy URLs.
10. send(request, stream=False, timeout=None, verify=True, cert=None, proxies=None)
發送 PreparedRequest 對象,返回 Response 對象
參數:
- request – 要發送的 PreparedRequest 對象
- stream – (可選) 是否 stream 請求的內容
- timeout (float 或 tuple) –(可選) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.
- verify – (可選) 是否驗證 SSL 證書
- cert – (可選) 可信任的用戶提供的 SSL 證書
- proxies – (可選) The proxies dictionary to apply to the request.
class requests.auth.AuthBase
所有認證的基類
class requests.auth.HTTPBasicAuth(username, password)
將 HTTP Basic Authentication 附加到給定的 Request 對象
class requests.auth.HTTPProxyAuth(username, password)
將 HTTP Proxy Authentication 附加到給定的 Request 對象
class requests.auth.HTTPDigestAuth(username, password)
將 HTTP Digest Authentication 附加到給定的 Request 對象
requests.utils.get_encodings_from_content(content)
返回給定內容的編碼格式
參數:
- content – 要從中提取編碼格式的 bytestring
requests.utils.get_encoding_from_headers(headers)
根據給定的 HTTP Header 字典返回編碼格式
參數:
- headers – 要從中提取編碼格式的字典
requests.utils.get_unicode_from_response(r)
以 unicode 返回響應內容
參數:
- r – 要從中提取編碼格式的 Response 對象
嘗試:
- content-type 里的字符集
- fall back and replace all unicode characters
requests.codes()
查詢狀態碼字典中對應的鍵/值
>>> requests.codes['temporary_redirect'] 307 >>> requests.codes.teapot 418 >>> requests.codes['\o/'] 200
