2011-10-08 36 views
18

我正在使用urllib2HTTPBasicAuthHandler像這樣的請求的urllib2要求:如何調試使用基本身份驗證處理

import urllib2 

theurl = 'http://someurl.com' 
username = 'username' 
password = 'password' 

passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passman.add_password(None, theurl, username, password) 

authhandler = urllib2.HTTPBasicAuthHandler(passman) 
opener = urllib2.build_opener(authhandler) 
urllib2.install_opener(opener) 

params = "foo=bar" 

response = urllib2.urlopen('http://someurl.com/somescript.cgi', params) 

print response.info() 

運行此代碼時,我目前得到一個httplib.BadStatusLine例外。我怎麼去調試?有沒有辦法查看原始響應是什麼,而不管無法識別的HTTP狀態碼?

回答

26

您是否嘗試過在您自己的HTTP處理程序中設置調試級別?更改您的代碼是這樣的:

>>> import urllib2 
>>> handler=urllib2.HTTPHandler(debuglevel=1) 
>>> opener = urllib2.build_opener(handler) 
>>> urllib2.install_opener(opener) 
>>> resp=urllib2.urlopen('http://www.google.com').read() 
send: 'GET/HTTP/1.1 
     Accept-Encoding: identity 
     Host: www.google.com 
     Connection: close 
     User-Agent: Python-urllib/2.7' 
reply: 'HTTP/1.1 200 OK' 
header: Date: Sat, 08 Oct 2011 17:25:52 GMT 
header: Expires: -1 
header: Cache-Control: private, max-age=0 
header: Content-Type: text/html; charset=ISO-8859-1 
... the remainder of the send/reply other than the data itself 

所以三行預先考慮是:

handler=urllib2.HTTPHandler(debuglevel=1) 
opener = urllib2.build_opener(handler) 
urllib2.install_opener(opener) 
... the rest of your urllib2 code... 

,將顯示在stderr原始HTTP發送/應答循環。從評論

編輯工作的呢?

... same code as above this line 
opener=urllib2.build_opener(authhandler, urllib2.HTTPHandler(debuglevel=1)) 
... rest of your code 
+0

我沒有看到一提的某處'HTTPHandler'了'debuglevel'參數,但該網站我與需求基本身份驗證通信,而據我所知'HTTPBasicAuthHandler'沒有調試選項。還有什麼我可以做的嗎?我設法找到了我的問題(錯誤的參數)的原因。 – Acorn

+0

回想一下[urllib2.build_opener()](http://docs.python.org/library/urllib2.html#urllib2.build_opener)的參數是鏈表的列表。您可以將您的調試http處理程序標記到您的身份驗證處理程序中...請參閱示例 –

+0

使用'urllib2.build_opener(authhandler,urllib2.HTTPHandler(debuglevel = 1))'我得到了調試輸出,但auth處理程序不起作用,我得到了'401未經授權的'。我已經嘗試了處理程序的切換順序(不確定這是否會產生任何影響),行爲也是一樣的。 – Acorn