2011-08-11 39 views
17

the urllib2 documentation爲什麼Python的urllib2.urlopen()爲成功的狀態代碼引發HTTPError?

因爲默認的處理程序處理重定向(在300範圍內的代碼),並在100-299範圍內的代碼表示成功,你通常只會看到在400-599範圍內的錯誤代碼。

然而下面的代碼

request = urllib2.Request(url, data, headers) 
response = urllib2.urlopen(request) 

引發引發HTTPError代碼爲201(創建):

ERROR 2011-08-11 20:40:17,318 __init__.py:463] HTTP Error 201: Created 

那麼,爲什麼urllib2扔HTTPErrors這個成功的請求?

這不是太痛苦;我可以很容易的代碼擴展到:

try: 
    request = urllib2.Request(url, data, headers) 
    response = urllib2.urlopen(request) 
except HTTPError, e: 
    if e.code == 201: 
     # success! :) 
    else: 
     # fail! :(
else: 
    # when will this happen...? 

但這似乎像預期的行爲不基於文檔和事實,我無法找到關於這個奇怪的行爲類似的問題上。

此外,又該else塊期待?如果成功的狀態碼都解釋爲HTTPError s,則什麼時候urllib2.urlopen()只返回一個正常的文件樣反應的物體,像所有的urllib2文件指的是?

+0

這真是不同尋常看到201-299之間的響應碼。沒有感到意外,urllib2並沒有完全處理它們。 – Leopd

+1

我錯過了什麼嗎? 201對我來說很好...... – Santa

+0

@Santa,根據dcrosta的回答,也許你正在使用非標準的處理程序? – rubergly

回答

3

由於實際文庫文檔中提到:

對於200錯誤代碼,響應對象被立即返回。

對於非200的錯誤代碼,這只是簡單地傳遞到protocol_error_code處理方法的作業,通過OpenerDirector.error()。最終,如果沒有其他處理程序處理該錯誤,urllib2.HTTPDefaultErrorHandler將引發一個HTTPError。

http://docs.python.org/library/urllib2.html#httperrorprocessor-objects

16

您可以編寫自定義Handler類與urllib2使用,以防止被提出作爲HTTError特定的錯誤代碼。這裏有一個我用之前:

class BetterHTTPErrorProcessor(urllib2.BaseHandler): 
    # a substitute/supplement to urllib2.HTTPErrorProcessor 
    # that doesn't raise exceptions on status codes 201,204,206 
    def http_error_201(self, request, response, code, msg, hdrs): 
     return response 
    def http_error_204(self, request, response, code, msg, hdrs): 
     return response 
    def http_error_206(self, request, response, code, msg, hdrs): 
     return response 

然後你可以使用它像:

opener = urllib2.build_opener(self.BetterHTTPErrorProcessor) 
urllib2.install_opener(opener) 

req = urllib2.Request(url, data, headers) 
urllib2.urlopen(req) 
+0

您在這些情況下如何確實檢查響應代碼? –

相關問題