首页  >  文章  >  后端开发  >  如何在Python中使用Requests\'PreparedRequest预览原始HTTP请求?

如何在Python中使用Requests\'PreparedRequest预览原始HTTP请求?

Patricia Arquette
Patricia Arquette原创
2024-10-23 15:46:02819浏览

How to Preview Raw HTTP Requests in Python Using Requests' PreparedRequest?

使用 Requests 在 Python 中打印原始 HTTP 请求

使用 Requests 模块时,您可能会遇到检查原始 HTTP 请求是有益的情况HTTP 请求正在发送到服务器。这不仅包括请求头,还包括请求行和内容。

使用PreparedRequest的解决方案:

从版本1.2.3开始,Requests引入了PreparedRequest对象。该对象表示“将发送到服务器的确切字节”,如下所示:https://requests.readthedocs.io/en/latest/advanced/prepared-requests-and-api/

要以漂亮的格式打印原始 HTTP 请求,您可以利用PreparedRequest 对象,如下所示:

<code class="python">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):
    """
    Formats and prints the prepared request in a readable manner.
    """
    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)

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

a=1&b=2</code>

这将以视觉上令人愉悦的格式显示请求行、标头和请求正文。

注意: Pretty_print_POST 函数中使用的格式是为了可读性而设计的,可能与发送的实际请求略有不同。

检查准备好的请求后,您可以继续使用请求会话发送实际请求,如下所示:

<code class="python">s = requests.Session()
s.send(prepared)</code>

有关准备好的请求和 API 等高级功能的更多详细信息,请参阅请求文档:https://requests.readthedocs.io/ en/latest/advanced/prepared-requests-and-api/

以上是如何在Python中使用Requests\'PreparedRequest预览原始HTTP请求?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn