# 11.7.?處理重定向
你可以使用兩種不同的自定義 URL 處理器來處理永久重定向和臨時重定向。
首先,讓我們來看看重定向處理的必要性。
## 例?11.10.?沒有重定向處理的情況下,訪問 web 服務
```
>>> import urllib2, httplib
>>> httplib.HTTPConnection.debuglevel = 1
>>> request = urllib2.Request(
... 'http://diveintomark.org/redir/example301.xml')
>>> opener = urllib2.build_opener()
>>> f = opener.open(request)
connect: (diveintomark.org, 80)
send: '
GET /redir/example301.xml HTTP/1.0
Host: diveintomark.org
User-agent: Python-urllib/2.1
'
reply: 'HTTP/1.1 301 Moved Permanently\r\n'
header: Date: Thu, 15 Apr 2004 22:06:25 GMT
header: Server: Apache/2.0.49 (Debian GNU/Linux)
header: Location: http://diveintomark.org/xml/atom.xml
header: Content-Length: 338
header: Connection: close
header: Content-Type: text/html; charset=iso-8859-1
connect: (diveintomark.org, 80)
send: '
GET /xml/atom.xml HTTP/1.0
Host: diveintomark.org
User-agent: Python-urllib/2.1
'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Thu, 15 Apr 2004 22:06:25 GMT
header: Server: Apache/2.0.49 (Debian GNU/Linux)
header: Last-Modified: Thu, 15 Apr 2004 19:45:21 GMT
header: ETag: "e842a-3e53-55d97640"
header: Accept-Ranges: bytes
header: Content-Length: 15955
header: Connection: close
header: Content-Type: application/atom+xml
>>> f.url
'http://diveintomark.org/xml/atom.xml'
>>> f.headers.dict
{'content-length': '15955',
'accept-ranges': 'bytes',
'server': 'Apache/2.0.49 (Debian GNU/Linux)',
'last-modified': 'Thu, 15 Apr 2004 19:45:21 GMT',
'connection': 'close',
'etag': '"e842a-3e53-55d97640"',
'date': 'Thu, 15 Apr 2004 22:06:25 GMT',
'content-type': 'application/atom+xml'}
>>> f.status
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: addinfourl instance has no attribute 'status'
```
| | |
| --- | --- |
| \[1\] | 你最好開啟調試狀態,看看發生了什么。 |
| \[2\] | 這是一個我已經設置了永久重定向到我的 Atom feed `http://diveintomark.org/xml/atom.xml` 的 URL。 |
| \[3\] | 毫無疑問,當你試圖從那個地址下載數據時,服務器會返回 `301` 狀態代碼,告訴你你訪問的資源已經被永久移動了。 |
| \[4\] | 服務器同時返回 `Location:` 頭信息,它給出了這個數據的新地址。 |
| \[5\] | `urllib2` 注意到了重定向狀態代碼并會自動從`Location:` 頭信息中給出的新地址獲取數據。 |
| \[6\] | 從 `opener` 返回的對象包括新的永久地址和第二次請求獲得的所有頭信息 (從一個新的永久地址獲得)。但是狀態代碼不見了,因此你無從知曉重定向到底是永久重定向還是臨時重定向。這是至關重要的:如果這是臨時重定向,那么你應該繼續使用舊地址訪問數據。但是如果是永久重定向 (正如本例),你應該從現在起使用新地址訪問數據。 |
這不太理想,但很容易改進。實際上當 `urllib2` 遇到 `301` 或 `302` 時的行為并不是我們所期望的,所以讓我們來覆蓋這些行為。如何實現呢?用一個自定義的處理器,[正如你處理 `304` 代碼所做的](etags.html "11.6.?處理 Last-Modified 和 ETag")。
## 例?11.11.?定義重定向處理器
這個類定義在 `openanything.py`。
```
class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
return result
def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
return result
```
| | |
| --- | --- |
| \[1\] | 重定向行為定義在 `urllib2` 的一個叫做 `HTTPRedirectHandler` 的類中。我們不想完全地覆蓋這些行為,只想做點擴展,所以我們子類化 `HTTPRedirectHandler`,從而我們仍然可以調用祖先類來實現所有原來的功能。 |
| \[2\] | 當從服務器獲得 `301` 狀態代碼,`urllib2` 將搜索處理器并調用 `http_error_301` 方法。我們首先要做的就是在祖先中調用 `http_error_301` 方法,它將處理查找 `Location:` 頭信息的工作并跟蹤重定向到新地址。 |
| \[3\] | 這是關鍵:返回之前,你存儲了狀態代碼 (`301`),所以主調程序稍后就可以訪問它了。 |
| \[4\] | 臨時重定向 (狀態代碼 `302`) 以相同的方式工作:覆蓋 `http_error_302` 方法,調用祖先,并在返回之前保存狀態代碼。 |
這將為我們帶來什么?現在你可以用自定義重定向處理器構造一個的 URL 開啟器,并且它依然能自動跟蹤重定向,也能展示出重定向狀態代碼。
## 例?11.12.?使用重定向處理器檢查永久重定向
```
>>> request = urllib2.Request('http://diveintomark.org/redir/example301.xml')
>>> import openanything, httplib
>>> httplib.HTTPConnection.debuglevel = 1
>>> opener = urllib2.build_opener(
... openanything.SmartRedirectHandler())
>>> f = opener.open(request)
connect: (diveintomark.org, 80)
send: 'GET /redir/example301.xml HTTP/1.0
Host: diveintomark.org
User-agent: Python-urllib/2.1
'
reply: 'HTTP/1.1 301 Moved Permanently\r\n'
header: Date: Thu, 15 Apr 2004 22:13:21 GMT
header: Server: Apache/2.0.49 (Debian GNU/Linux)
header: Location: http://diveintomark.org/xml/atom.xml
header: Content-Length: 338
header: Connection: close
header: Content-Type: text/html; charset=iso-8859-1
connect: (diveintomark.org, 80)
send: '
GET /xml/atom.xml HTTP/1.0
Host: diveintomark.org
User-agent: Python-urllib/2.1
'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Thu, 15 Apr 2004 22:13:21 GMT
header: Server: Apache/2.0.49 (Debian GNU/Linux)
header: Last-Modified: Thu, 15 Apr 2004 19:45:21 GMT
header: ETag: "e842a-3e53-55d97640"
header: Accept-Ranges: bytes
header: Content-Length: 15955
header: Connection: close
header: Content-Type: application/atom+xml
>>> f.status
301
>>> f.url
'http://diveintomark.org/xml/atom.xml'
```
| | |
| --- | --- |
| \[1\] | 首先,用剛剛定義的重定向處理器創建一個 URL 開啟器。 |
| \[2\] | 你發送了一個請求,并在響應中獲得了 `301` 狀態代碼。 如此一來,`http_error_301` 方法就被調用了。你調用了祖先類,跟蹤了重定向并且發送了一個新地址 (`http://diveintomark.org/xml/atom.xml`) 請求。 |
| \[3\] | 這是決定性的一步:現在,你不僅做到了訪問一個新 URL,而且獲得了重定向的狀態代碼,所以你可以斷定這是一個永久重定向。下一次你請求這個數據時,就應該使用 `f.url` 指定的新地址 (`http://diveintomark.org/xml/atom.xml`)。如果你已經在配置文件或數據庫中存儲了這個地址,就需要更新舊地址而不是反復地使用舊地址請求服務。現在是更新你的地址簿的時候了。 |
同樣的重定向處理也可以告訴你_不該_ 更新你的地址簿。
## 例?11.13.?使用重定向處理器檢查臨時重定向
```
>>> request = urllib2.Request(
... 'http://diveintomark.org/redir/example302.xml')
>>> f = opener.open(request)
connect: (diveintomark.org, 80)
send: '
GET /redir/example302.xml HTTP/1.0
Host: diveintomark.org
User-agent: Python-urllib/2.1
'
reply: 'HTTP/1.1 302 Found\r\n'
header: Date: Thu, 15 Apr 2004 22:18:21 GMT
header: Server: Apache/2.0.49 (Debian GNU/Linux)
header: Location: http://diveintomark.org/xml/atom.xml
header: Content-Length: 314
header: Connection: close
header: Content-Type: text/html; charset=iso-8859-1
connect: (diveintomark.org, 80)
send: '
GET /xml/atom.xml HTTP/1.0
Host: diveintomark.org
User-agent: Python-urllib/2.1
'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Thu, 15 Apr 2004 22:18:21 GMT
header: Server: Apache/2.0.49 (Debian GNU/Linux)
header: Last-Modified: Thu, 15 Apr 2004 19:45:21 GMT
header: ETag: "e842a-3e53-55d97640"
header: Accept-Ranges: bytes
header: Content-Length: 15955
header: Connection: close
header: Content-Type: application/atom+xml
>>> f.status
302
>>> f.url
http://diveintomark.org/xml/atom.xml
```
| | |
| --- | --- |
| \[1\] | 這是一個 URL,我已經設置了它,讓它告訴客戶端_臨時_ 重定向到 `http://diveintomark.org/xml/atom.xml`。 |
| \[2\] | 服務器返回 `302` 狀態代碼,標識出一個臨時重定向。數據的臨時新地址在 `Location:` 頭信息中給出。 |
| \[3\] | `urllib2` 調用你的 `http_error_302` 方法,它調用了 `urllib2.HTTPRedirectHandler` 中的同名的祖先方法,跟蹤重定向到一個新地址。然后你的 `http_error_302` 方法存儲狀態代碼 (`302`) 使主調程序在稍后可以獲得它。 |
| \[4\] | 此時,已經成功追蹤重定向到 `http://diveintomark.org/xml/atom.xml`。`f.status` 告訴你這是一個臨時重定向,這意味著你應該繼續使用原來的地址 (`http://diveintomark.org/redir/example302.xml`) 請求數據。也許下一次它仍然被重定向,也許不會。也許會重定向到不同的地址。這也不好說。服務器說這個重定向僅僅是臨時的,你應該尊重它。并且現在你獲得了能使主調程序尊重它的充分信息。 |
- 版權信息
- 第?1?章?安裝 Python
- 1.1.?哪一種 Python 適合您?
- 1.2.?Windows 上的 Python
- 1.3.?Mac OS X 上的 Python
- 1.4.?Mac OS 9 上的 Python
- 1.5.?RedHat Linux 上的 Python
- 1.6.?Debian GNU/Linux 上的 Python
- 1.7.?從源代碼安裝 Python
- 1.8.?使用 Python 的交互 Shell
- 1.9.?小結
- 第?2?章?第一個 Python 程序
- 2.1.?概覽
- 2.2.?函數聲明
- 2.3.?文檔化函數
- 2.4.?萬物皆對象
- 2.5.?代碼縮進
- 2.6.?測試模塊
- 第?3?章?內置數據類型
- 3.1.?Dictionary 介紹
- 3.2.?List 介紹
- 3.3.?Tuple 介紹
- 3.4.?變量聲明
- 3.5.?格式化字符串
- 3.6.?映射 list
- 3.7.?連接 list 與分割字符串
- 3.8.?小結
- 第?4?章?自省的威力
- 4.1.?概覽
- 4.2.?使用可選參數和命名參數
- 4.3.?使用 type、str、dir 和其它內置函數
- 4.4.?通過 getattr 獲取對象引用
- 4.5.?過濾列表
- 4.6.?and 和 or 的特殊性質
- 4.7.?使用 lambda 函數
- 4.8.?全部放在一起
- 4.9.?小結
- 第?5?章?對象和面向對象
- 5.1.?概覽
- 5.2.?使用 from _module_ import 導入模塊
- 5.3.?類的定義
- 5.4.?類的實例化
- 5.5.?探索 UserDict:一個封裝類
- 5.6.?專用類方法
- 5.7.?高級專用類方法
- 5.8.?類屬性介紹
- 5.9.?私有函數
- 5.10.?小結
- 第?6?章?異常和文件處理
- 6.1.?異常處理
- 6.2.?與文件對象共事
- 6.3.?for 循環
- 6.4.?使用 `sys.modules`
- 6.5.?與目錄共事
- 6.6.?全部放在一起
- 6.7.?小結
- 第?7?章?正則表達式
- 7.1.?概覽
- 7.2.?個案研究:街道地址
- 7.3.?個案研究:羅馬字母
- 7.4.?使用 {n,m} 語法
- 7.5.?松散正則表達式
- 7.6.?個案研究:解析電話號碼
- 7.7.?小結
- 第?8?章?HTML 處理
- 8.1.?概覽
- 8.2.?sgmllib.py 介紹
- 8.3.?從 HTML 文檔中提取數據
- 8.4.?BaseHTMLProcessor.py 介紹
- 8.5.?locals 和 globals
- 8.6.?基于 dictionary 的字符串格式化
- 8.7.?給屬性值加引號
- 8.8.?dialect.py 介紹
- 8.9.?全部放在一起
- 8.10.?小結
- 第?9?章?XML 處理
- 9.1.?概覽
- 9.2.?包
- 9.3.?XML 解析
- 9.4.?Unicode
- 9.5.?搜索元素
- 9.6.?訪問元素屬性
- 9.7.?Segue [9]
- 第?10?章?腳本和流
- 10.1.?抽象輸入源
- 10.2.?標準輸入、輸出和錯誤
- 10.3.?查詢緩沖節點
- 10.4.?查找節點的直接子節點
- 10.5.?根據節點類型創建不同的處理器
- 10.6.?處理命令行參數
- 10.7.?全部放在一起
- 10.8.?小結
- 第?11?章?HTTP Web 服務
- 11.1.?概覽
- 11.2.?避免通過 HTTP 重復地獲取數據
- 11.3.?HTTP 的特性
- 11.4.?調試 HTTP web 服務
- 11.5.?設置 User-Agent
- 11.6.?處理 Last-Modified 和 ETag
- 11.7.?處理重定向
- 11.8.?處理壓縮數據
- 11.9.?全部放在一起
- 11.10.?小結
- 第?12?章?SOAP Web 服務
- 12.1.?概覽
- 12.2.?安裝 SOAP 庫
- 12.3.?步入 SOAP
- 12.4.? SOAP 網絡服務查錯
- 12.5.?WSDL 介紹
- 12.6.?以 WSDL 進行 SOAP 內省
- 12.7.?搜索 Google
- 12.8.? SOAP 網絡服務故障排除
- 12.9.?小結
- 第?13?章?單元測試
- 13.1.?羅馬數字程序介紹 II
- 13.2.?深入
- 13.3.?romantest.py 介紹
- 13.4.?正面測試 (Testing for success)
- 13.5.?負面測試 (Testing for failure)
- 13.6.?完備性檢測 (Testing for sanity)
- 第?14?章?測試優先編程
- 14.1.?roman.py, 第 1 階段
- 14.2.?roman.py, 第 2 階段
- 14.3.?roman.py, 第 3 階段
- 14.4.?roman.py, 第 4 階段
- 14.5.?roman.py, 第 5 階段
- 第?15?章?重構
- 15.1.?處理 bugs
- 15.2.?應對需求變化
- 15.3.?重構
- 15.4.?后記
- 15.5.?小結
- 第?16?章?函數編程
- 16.1.?概覽
- 16.2.?找到路徑
- 16.3.?重識列表過濾
- 16.4.?重識列表映射
- 16.5.?數據中心思想編程
- 16.6.?動態導入模塊
- 16.7.?全部放在一起
- 16.8.?小結
- 第?17?章?動態函數
- 17.1.?概覽
- 17.2.?plural.py, 第 1 階段
- 17.3.?plural.py, 第 2 階段
- 17.4.?plural.py, 第 3 階段
- 17.5.?plural.py, 第 4 階段
- 17.6.?plural.py, 第 5 階段
- 17.7.?plural.py, 第 6 階段
- 17.8.?小結
- 第?18?章?性能優化
- 18.1.?概覽
- 18.2.?使用 timeit 模塊
- 18.3.?優化正則表達式
- 18.4.?優化字典查找
- 18.5.?優化列表操作
- 18.6.?優化字符串操作
- 18.7.?小結
- 附錄?A.?進一步閱讀
- 附錄?B.?五分鐘回顧
- 附錄?C.?技巧和竅門
- 附錄?D.?示例清單
- 附錄?E.?修訂歷史
- 附錄?F.?關于本書
- 附錄 G. GNU Free Documentation License
- G.0. Preamble
- G.1.?Applicability and definitions
- G.2.?Verbatim copying
- G.3.?Copying in quantity
- G.4.?Modifications
- G.5.?Combining documents
- G.6.?Collections of documents
- G.7.?Aggregation with independent works
- G.8.?Translation
- G.9.?Termination
- G.10.?Future revisions of this license
- G.11.?How to use this License for your documents
- 附錄 H. GNU 自由文檔協議
- H.0. 序
- H.1.?適用范圍和定義
- H.2.?原樣復制
- H.3.?大量復制
- H.4.?修改
- H.5.?合并文檔
- H.6.?文檔合集
- H.7.?獨立著作聚集
- H.8.?翻譯
- H.9.?終止協議
- H.10.?協議將來的修訂
- H.11.?如何為你的文檔使用本協議
- 附錄 I. Python license
- I.A. History of the software
- I.B.?Terms and conditions for accessing or otherwise using Python
- 附錄 J. Python 協議
- J.0. 關于譯文的聲明
- J.A.?軟件的歷史
- J.B.?使用 Python 的條款和條件