python
主页 > 脚本 > python >

Python实现打印http请求信息

2024-06-28 | 佚名 | 点击:

问题

我们在开发过程中,为了快速验证接口,

经常采用postman或者Python代码先行验证的方式,确保接口正常,

在测试接口过程中偶尔会遇到接口异常,这时候要和打印完整的http请求,

帮助接口开发人员确认问题;

方法

仅仅是打印出这些信息,很简单:

1

2

3

4

import requests

response = requests.post('http://httpbin.org/post', data={'key1':'value1'})

print(response.request.headers)

print(response.request.body)

或者:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import requests

 

def pretty_print_POST(req):

    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,

    ))

 

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

prepared = req.prepare()

pretty_print_POST(prepared)

 

s = requests.Session()

resp = s.send(prepared)

print(resp.text)

但如果你想要在进行请求之前对http头和数据进行操作,也是使用prepare:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

from requests import Request, Session

 

s = Session()

 

req = Request('POST', url, data=data, headers=headers)

prepped = req.prepare()

 

# do something with prepped.body

prepped.body = 'No, I want exactly this as the body.'

 

# do something with prepped.headers

del prepped.headers['Content-Type']

 

resp = s.send(prepped,

    stream=stream,

    verify=verify,

    proxies=proxies,

    cert=cert,

    timeout=timeout

)

 

print(resp.status_code)

python 的库的用法去对应的库的帮助文档里去找,更为方便些;

原文链接:
相关文章
最新更新