Python请求 - 打印整个http请求(原始)? [英] Python requests - print entire http request (raw)?
问题描述
使用 requests
模块,有没有办法打印原始HTTP请求?
While using the requests
module, is there any way to print the raw HTTP request?
我不想只是标题,我想要请求行,标题和内容打印输出。是否有可能看到最终由HTTP请求构造的内容?
I don't want just the headers, I want the request line, headers, and content printout. Is it possible to see what ultimately is constructed from HTTP request?
推荐答案
自v1.2.3起请求添加了PreparedRequest对象。根据文档它包含将发送到服务器的确切字节。
Since v1.2.3 Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server".
可以使用它来打印请求,如下所示:
One can use this to pretty print a request, like so:
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{}\n{}\n\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\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
然后你可以发送实际的请求:
Then you can send the actual request with this:
s = requests.Session()
s.send(prepared)
这些链接是最新的文档可用,因此它们可能会更改内容:
高级 - 准备好的请求和 API - 低级别课程
These links are to the latest documentation available, so they might change in content: Advanced - Prepared requests and API - Lower level classes
这篇关于Python请求 - 打印整个http请求(原始)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!