如何查看 Python 应用程序发送的整个 HTTP 请求?

问题描述:

就我而言,我使用 requests 库通过 HTTPS 调用 PayPal 的 API.不幸的是,我收到了来自 PayPal 的错误消息,而 PayPal 支持人员无法弄清楚错误是什么或导致错误的原因.他们希望我请提供整个请求,包括标题".

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".

我该怎么做?

一个简单的方法:在最新版本的 Requests(1.x 及更高版本)中启用日志记录.

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

Requests 使用 http.clientlogging 模块配置来控制日志记录的详细程度,如此处.

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

从链接文档中摘录的代码:

Code excerpted from the linked documentation:

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
Host: httpbin.org
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic

'
reply: 'HTTP/1.1 200 OK
'
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