Skip to content

Instantly share code, notes, and snippets.

@mapix
Created May 16, 2017 15:20
Show Gist options
  • Save mapix/a386f721e75c3a611afee70127f75b2b to your computer and use it in GitHub Desktop.
Save mapix/a386f721e75c3a611afee70127f75b2b to your computer and use it in GitHub Desktop.
Enable python requests logging debug info
def enable_requests_debug():
from random import choice
from requests.packages.urllib3 import HTTPResponse
from requests.packages.urllib3.packages.six.moves import http_client
if getattr(HTTPResponse, 'has_enable_requests_debug', False):
return
RESET_COLOR = '\033[0m'
COLORS = ['\033[95m', '\033[94m', '\033[92m', '\033[93m', '\033[91m', '\033[1m']
http_client.HTTPConnection.debuglevel = 1
origin_putrequest = http_client.HTTPConnection.putrequest
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
print "{}>>>>>>>>>>>>>>> BEGIN [{}:{}] ".format(choice(COLORS), method, url)
return origin_putrequest(self, method, url, skip_host=skip_host, skip_accept_encoding=skip_accept_encoding)
http_client.HTTPConnection.putrequest = putrequest
origin_read = HTTPResponse.read
def read(self, *args, **kwargs):
data = origin_read(self, *args, **kwargs)
print
print data
print "<<<<<<<<<<<<<<< END [{}]{}".format(self._original_response._method, RESET_COLOR)
return data
HTTPResponse.read = read
setattr(HTTPResponse, 'has_enable_requests_debug', True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment