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('{}
{}
{}
{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'
'.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屋!