2019年11月1日 星期五

[ Python 常見問題 ] How can I see the entire HTTP request that's being sent by my Python application?

Source From Here
Question
In my case, I'm using the requests library to call PayPal's API over HTTPS. Unfortunately, I'm getting an error from PayPal, and PayPal support cannot figure out what the error is or what's causing it. They want me to "Please provide the entire request, headers included".

How can I do that?

How-To
A simple method: enable logging in recent versions of Requests (1.x and higher.)

Requests uses the http.client and logging module configuration to control logging verbosity, as described here.

Demonstration
Code excerpted from the linked documentation:
  1. import requests  
  2. import logging  
  3.   
  4. # These two lines enable debugging at httplib level (requests->urllib3->http.client)  
  5. # You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.  
  6. # The only thing missing will be the response.body which is not logged.  
  7. try:  
  8.     import http.client as http_client  
  9. except ImportError:  
  10.     # Python 2  
  11.     import httplib as http_client  
  12. http_client.HTTPConnection.debuglevel = 1  
  13.   
  14. # You must initialize logging, otherwise you'll not see debug output.  
  15. logging.basicConfig()  
  16. logging.getLogger().setLevel(logging.DEBUG)  
  17. requests_log = logging.getLogger("requests.packages.urllib3")  
  18. requests_log.setLevel(logging.DEBUG)  
  19. requests_log.propagate = True  
  20.   
  21. requests.get('https://httpbin.org/headers')  
Example Output
$ python requests-logging.py
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...