使用requests模块时,有没有办法打印原始 HTTP 请求?
requests
我不只想要标题,我想要请求行、标题和内容打印输出。是否可以看到最终由 HTTP 请求构造的内容?
由于 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)
这些链接指向可用的最新文档,因此它们的内容可能会发生变化: 高级 - 准备好的请求和API - 较低级别的类