changeset 11:e7dfad8c8f27

add option to log requests to a file
author Jeff Hammel <jhammel@mozilla.com>
date Fri, 26 Nov 2010 12:18:35 -0800
parents 3cdbc94626b8
children ee0f793a649a
files bzconsole/main.py
diffstat 1 files changed, 37 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/bzconsole/main.py	Sat Nov 06 16:32:07 2010 -0700
+++ b/bzconsole/main.py	Fri Nov 26 12:18:35 2010 -0800
@@ -3,6 +3,7 @@
 console API to bugzilla
 """
 
+import httplib
 import json
 import os
 import subprocess
@@ -10,6 +11,8 @@
 import urllib
 import urllib2
 
+from StringIO import StringIO
+
 from command import CommandParser
 from utils import tmpbuffer
 
@@ -25,13 +28,16 @@
     def __init__(self,
                  server='https://api-dev.bugzilla.mozilla.org/latest',
                  refresh=False,
+                 print_request=None,
                  username=None,
                  password=None):
         """
-        - refresh : refresh the (cached) configuration        
+        - refresh : refresh the (cached) configuration
+        - print_request : print out the request, dont actually open
         """
         self.server = server
         self.refresh = refresh
+        self.print_request = print_request
         self.username = username
         self.password = password
 
@@ -117,6 +123,36 @@
         if data:
             data = json.dumps(data)
         req = urllib2.Request(url, data, headers)
+
+        # print out the request
+        # from http://stackoverflow.com/questions/603856/how-do-you-get-default-headers-in-a-urllib2-request
+        if self.print_request:
+
+            f = file(self.print_request, 'a')
+            class MyHTTPConnection(httplib.HTTPConnection):
+                def send(self, s):
+                    print >> f, s  # or save them, or whatever!
+                    httplib.HTTPConnection.send(self, s)
+
+            class MyHTTPSConnection(httplib.HTTPSConnection):
+                def send(self, s):
+                    print >> f, s
+                    httplib.HTTPSConnection.send(self, s)
+
+            class MyHTTPHandler(urllib2.HTTPHandler):
+                def http_open(self, req):
+                    return self.do_open(MyHTTPConnection, req)
+            class MyHTTPSHandler(urllib2.HTTPSHandler):
+                def https_open(self, req):
+                    return self.do_open(MyHTTPSConnection, req)
+
+            if self.server.startswith('https://'):
+                opener = urllib2.build_opener(MyHTTPSHandler)
+            else:
+                opener = urllib2.build_opener(MyHTTPHandler)
+            opener.open(req)
+            return
+        
         try:
             response = urllib2.urlopen(req)
         except Exception, e: