接著,文件中說明Response的status code
和Header
的部分
staus code相關的屬性與方法,r.status_code
和r.raise_for_status()
。其中raise_for_status()是針對4XX client error或是5XX server error使用。另外requests本身有提供較語意化的存取方式,例如: requests.codes.ok,若想參考其他code的定義,可以參考status_codes.py
Header可以使用r.headers
取得,需要注意的是存取時可不分大小寫
繼續說明的部分是Cookies
, Redirection and History
, Timeouts
以及Errors and Exceptions
cookies可以用r.cookies
取得,若需要送出的話,可以用dictionary或RequestsCookieJar,後者可以達成更詳細的設定,例如:domain, path
Cookies are returned in a RequestsCookieJar, which acts like a dict but also offers a more complete interface, suitable for use over multiple domains or paths. Cookie jars can also be passed in to requests
關於重導向,除了HEAD Method之外,Requests package預設會自動重導向,並提供開關(allow_redirects)可以設定。r.history
主要用在追蹤重導向的過程中所創建的Response物件,會依照創建時間排序。
關於Timeout,除非特別設定,Requests package預設是沒有timeout行為。需要注意的是這個值代表的含意並非等整個Response都回傳完成,而是底層socket沒有接收到任何資料。
timeout is not a time limit on the entire response download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out.
最後,Requests定義了幾種Errors and Exceptions
Errors and Exceptions | Description |
---|---|
ConnectionError | network problem (e.g. DNS failure, refused connection, etc) |
HTTPError | HTTP request returned an unsuccessful status code |
Timeout | a request times out |
TooManyRedirects | a request exceeds the configured number of maximum redirections |
整理一下到目前為止提到的幾個屬性和方法
r = requests.get('https://api.github.com/events', stream=True)
r.headers
r.url
r.cookies
r.encoding
r.text
r.status_code
r.raise_for_status()
r.content
r.json()
r.raw
r.iter_content()
r.history