如何调试使用基本身份验证处理程序的urllib2请求

时间:2011-10-08 15:56:04

标签: python debugging urllib2 basic-authentication

我正在使用urllib2HTTPBasicAuthHandler这样的请求:

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状态代码?

1 个答案:

答案 0 :(得分:27)

您是否尝试在自己的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