就我而言,我正在使用该requests库通过HTTPS调用PayPal的API。不幸的是,我从贝宝(PayPal)收到一个错误,贝宝(PayPal)支持人员无法弄清楚该错误是什么或由什么引起的。他们希望我“请提供整个请求,包括标头”。
requests
我怎样才能做到这一点?
一种简单的方法:启用登录最新版本的请求(1.x及更高版本)。
请求用途http.client和logging模块配置到控制日志记录级别,如所描述这里。
示范 摘自链接文档的代码:
import requests import logging # These two lines enable debugging at httplib level (requests->urllib3->http.client) # You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA. # The only thing missing will be the response.body which is not logged. try: import http.client as http_client except ImportError: # Python 2 import httplib as http_client http_client.HTTPConnection.debuglevel = 1 # You must initialize logging, otherwise you'll not see debug output. logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True requests.get('https://httpbin.org/headers')
示例输出
$ 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