如果在處理過程中發生錯誤,則response.raise_for_status()返回HTTPError對象。它用於調試請求模塊,並且是Python請求的組成部分。 Python請求通常用於從特定資源URI中獲取內容。每當我們通過Python向指定URI發出請求時,它都會返回一個響應對象。現在,此響應對象將用於訪問某些函數,例如內容,標頭等。本文圍繞如何檢查響應進行說明。raise_for_status()來自響應對象。
如何通過Python請求使用response.raise_for_status()?
為了說明對response.raise_for_status()的使用,讓我們ping github.com和geeksforgeeks.org。要運行此腳本,您需要在PC上安裝Python和請求。
先決條件-
示例代碼-
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com/')
# print response
print(response)
# print check if an error has occurred
print(response.raise_for_status())
# ping an incorrect url
response = requests.get('https://geeksforgeeks.org / naveen/')
# print check if an error has occurred
print(response.raise_for_status())
示例實現-
將以上文件另存為request.py
並使用
Python request.py
輸出-
檢查Traceback錯誤,它表明已發生錯誤以及錯誤“Invalid URL”和狀態代碼404。
先進概念
使用Python發出HTTP請求的庫有很多,例如httplib,urllib,httplib2,treq等,但是請求是具有出色函數的最好的庫之一。如果請求的任何屬性顯示為NULL,請使用以下屬性檢查狀態代碼。
requests.status_code
如果status_code不在200-29範圍內。您可能需要檢查開始用於請求的方法+您正在請求的URL的資源。
相關用法
- Python response.url用法及代碼示例
- Python response.ok用法及代碼示例
- Python response.is_redirect用法及代碼示例
- Python response.json()用法及代碼示例
- Python response.text用法及代碼示例
- Python response.status_code用法及代碼示例
- Python response.request用法及代碼示例
- Python response.reason用法及代碼示例
- Python response.iter_content()用法及代碼示例
- Python response.elapsed用法及代碼示例
- Python response.close()用法及代碼示例
- Python response.content用法及代碼示例
注:本文由純淨天空篩選整理自NaveenArora大神的英文原創作品 response.raise_for_status() – Python requests。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。