讀取狀態程式碼
屬性 status_code
包含響應的狀態程式碼
good_req = requests.get('https://api.github.com/events')
code_200 = good_req.status_code
notfound_req = requests.get('https://api.github.com/not_found')
code_404 = notfound_req.status_code
requests.codes.__dict__
將提供可用的 http 狀態程式碼列表。
使用者 raise_for_status
可以檢查 status_code 是 4xx 還是 5xx,並在這種情況下引發相應的異常。
good_req = requests.get('https://api.github.com/events')
good_req.raise_for_status()
# is a 200 status code so nothing happens
notfound_req = requests.get('https://api.github.com/not_found')
notfound_req.raise_for_status()
# raises requests.exceptions.HTTPError: 404 Client Error