Python请求 - 打印整个http请求(原始)?

使用 requests module 时,有没有办法打印原始 HTTP 请求?

我不只想要标题,我想要请求行、标题和内容打印输出。是否可以看到最终由 HTTP 请求构造的内容?

最佳答案

Since v1.2.3 Requests 添加了 PreparedRequest 对象。根据文档“它包含将发送到服务器的确切字节”。

可以使用它来漂亮地打印请求,如下所示:

import requests

req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()

def pretty_print_POST(req):
    """
    At this point it is completely built and ready
    to be fired; it is "prepared".

    However pay attention at the formatting used in 
    this function because it is programmed to be pretty 
    printed and may differ from the actual request.
    """
    print('{}\n{}\r\n{}\r\n\r\n{}'.format(
        '-----------START-----------',
        req.method + ' ' + req.url,
        '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
        req.body,
    ))

pretty_print_POST(prepared)

产生:

-----------START-----------
POST http://stackoverflow.com/
Content-Length: 7
X-Custom: Test

a=1&b=2

然后你可以用这个发送实际的请求:

s = requests.Session()
s.send(prepared)

这些链接指向可用的最新文档,因此它们的内容可能会有所变化: Advanced - Prepared requests和 API - Lower level classes

https://stackoverflow.com/questions/20658572/

相关文章:

linux - Linux 上的 PostgreSQL 数据库默认位置

c - DESTDIR 和 PREFIX 的 make

python - 检查数字是 int 还是 float

linux - 我可以使用 GDB 调试正在运行的进程吗?

linux - 如何根据字段的数值对文件进行排序?

python - 设置 Django 以使用 MySQL

Python 请求 - 无连接适配器

linux - 如何将 AWS CLI 升级到最新版本?

python - 在 Python 中格式化多行 dict 的正确方法是什么?

python - Python NumPy 中的 np.mean() 与 np.average()?