在我的例子中,我使用requests库通过HTTPS调用PayPal的API.不幸的是,我从PayPal收到了一个错误,而PayPal的支持人员无法找出错误是什么,或者是什么导致的.他们希望我"请提供整个请求,包括标题".

我该怎么做?

推荐答案

一种简单的方法:在请求的最新版本(1.x和更高版本)中启用日志(log)记录.

请求使用http.clientlogging模块配置来控制日志(log)记录详细程度,如here所述.

游行示威

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

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

Python相关问答推荐

我们可以在apps.py?中使用Post_Save信号吗

为什么自定义pytree aux_data对于jnp.数组来说在.jit()之后跟踪,而对于np.数组来说则不是?

从多行文本中提取事件对

如何判断LazyFrame是否为空?

绘制系列时如何反转轴?

如何销毁框架并使其在tkinter中看起来像以前的样子?

在Python和matlab中显示不同 colored颜色 的图像

如何让 turtle 通过点击和拖动来绘制?

Python会扔掉未使用的表情吗?

如何自动抓取以下CSV

将特定列信息移动到当前行下的新行

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

输出中带有南的亚麻神经网络

在Pandas DataFrame操作中用链接替换'方法的更有效方法

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

SQLAlchemy Like ALL ORM analog

Python Tkinter为特定样式调整所有ttkbootstrap或ttk Button填充的大小,适用于所有主题

未调用自定义JSON编码器

重置PD帧中的值

python—telegraph—bot send_voice发送空文件