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

Aco*_*orn 19 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()
Run Code Online (Sandbox Code Playgroud)

我正在httplib.BadStatusLine运行此代码时遇到异常.我怎么去调试?有没有办法看到原始响应是什么,无论无法识别的HTTP状态代码?

the*_*olf 28

您是否尝试在自己的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 
Run Code Online (Sandbox Code Playgroud)

所以前面提到的三条线是:

handler=urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
... the rest of your urllib2 code...
Run Code Online (Sandbox Code Playgroud)

这将显示stderr上的原始HTTP发送/回复周期.

从评论编辑

这有用吗?

... same code as above this line
opener=urllib2.build_opener(authhandler, urllib2.HTTPHandler(debuglevel=1))
... rest of your code
Run Code Online (Sandbox Code Playgroud)

  • 请注意,对于https,您需要将其更改为urllib2.HTTPSHandler(debuglevel = 1) (6认同)