栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 打印http请求信息

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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{}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 的库的用法去对应的库的帮助文档里去找,更为方便些;

  1. Python requests - print entire http request (raw)?
  2. Request and Response Objects
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/833764.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号