Python实现打印http请求信息
问题我们在开发过程中,为了快速验证接口,
经常采用postman或者Python代码先行验证的方式,确保接口正常,
在测试接口过程中偶尔会遇到接口异常,这时候要和打印完整的http请求,
帮助接口开发人员确认问题;
方法
仅仅是打印出这些信息,很简单:
import requests
response = requests.post('http://httpbin.org/post', data={'key1':'value1'})
print(response.request.headers)
print(response.request.body)或者:
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:
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 的库的用法去对应的库的帮助文档里去找,更为方便些;
[*]Python requests - print entire http request (raw)?
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源:https://www.jb51.net/python/323450sdr.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]