views:

353

answers:

2

How can I watch the messages being sent back and for on urllib shttp requests? If it were simple http I would just watch the socket traffic but of course that won't work for https. Is there a debug flag I can set that will do this?

import urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen("https://example.com/cgi-bin/query", params)
+1  A: 

No, there's no debug flag to watch this.

You can use your favorite debugger. It is the easiest option. Just add a breakpoint in the urlopen function and you're done.

Another option would be to write your own download function:

def graburl(url, **params):
    print "LOG: Going to %s with %r" % (url, params)
    params = urllib.urlencode(params)
    return urllib.urlopen(url, params)

And use it like this:

f = graburl("https://example.com/cgi-bin/query", spam=1, eggs=2, bacon=0)
nosklo
+1  A: 

You can always do a little bit of mokeypatching

import httplib

# override the HTTPS request class

class DebugHTTPS(httplib.HTTPS):
    real_putheader = httplib.HTTPS.putheader
    def putheader(self, *args, **kwargs):
        print 'putheader(%s,%s)' % (args, kwargs)
        result = self.real_putheader(self, *args, **kwargs)
        return result

httplib.HTTPS = DebugHTTPS



# set a new default urlopener

import urllib

class DebugOpener(urllib.FancyURLopener):
    def open(self, *args, **kwargs):
        result = urllib.FancyURLopener.open(self, *args, **kwargs)
        print 'response:'
        print result.headers
        return result

urllib._urlopener = DebugOpener()


params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) 
f = urllib.urlopen("https://www.google.com/", params)

gives the output

putheader(('Content-Type', 'application/x-www-form-urlencoded'),{})
putheader(('Content-Length', '21'),{})
putheader(('Host', 'www.google.com'),{})
putheader(('User-Agent', 'Python-urllib/1.17'),{})
response:
Content-Type: text/html; charset=UTF-8
Content-Length: 1363
Date: Sun, 09 Aug 2009 12:49:59 GMT
Server: GFE/2.0
Otto Allmendinger