web-dev-qa-db-ja.com

基本認証ハンドラーを使用するurllib2要求をデバッグする方法

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ステータスコードに関係なく、生の応答が何であるかを確認する方法はありますか?

19
Acorn

独自の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 

したがって、追加する3行は次のとおりです。

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
27
the wolf