目录
- 问题
- 方法
- 总结
问题
我们在开发过程中,为了快速验证接口,
经常采用postman或者python代码先行验证的方式,确保接口正常,
在测试接口过程中偶尔会遇到接口异常,这时候要和打印完整的http请求,
帮助接口开发人员确认问题;
方法
仅仅是打印出这些信息,很简单:
import requests response = requests.post('http://httpbin.org/post', data={'key1':'value1'}) print(respandroidonse.request.headers) print(response.request.body)
或者:
import requests def pretty_print_POST(req): print('{}\n{}\r\n{}\r\n\r\n{}'.format( '-----------STAandroidRT-----------', req.method + ' ' + req.url, '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items())qzDpA, 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(preppythonared) 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 = python'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)?
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论