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

新手上路,请多包涵

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

我怎样才能做到这一点?

原文由 Chris B. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 980
2 个回答

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

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

示范

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

 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

原文由 Inactivist 发布,翻译遵循 CC BY-SA 4.0 许可协议

r = requests.get('https://api.github.com', auth=('user', 'pass'))

r 是一个回应。它有一个请求属性,其中包含您需要的信息。

 r.request.allow_redirects  r.request.headers          r.request.register_hook
r.request.auth             r.request.hooks            r.request.response
r.request.cert             r.request.method           r.request.send
r.request.config           r.request.params           r.request.sent
r.request.cookies          r.request.path_url         r.request.session
r.request.data             r.request.prefetch         r.request.timeout
r.request.deregister_hook  r.request.proxies          r.request.url
r.request.files            r.request.redirect         r.request.verify

r.request.headers 给出标题:

 {'Accept': '*/*',
 'Accept-Encoding': 'identity, deflate, compress, gzip',
 'Authorization': u'Basic dXNlcjpwYXNz',
 'User-Agent': 'python-requests/0.12.1'}

然后 r.request.data 将正文作为映射。如果他们愿意,您可以使用 urllib.urlencode 转换它:

 import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)

根据响应的类型, .data 可能会丢失,而 .body 会出现。

原文由 Skylar Saveland 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题