问题
我们在开发过程中,为了快速验证接口,
经常采用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{}rn{}rnrn{}'.format( '-----------START-----------', req.method + ' ' + req.url, 'rn'.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 的库的用法去对应的库的帮助文档里去找,更为方便些;
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。