python requests模块作用_python的requests模块

使用python进行接口测试得时候可以使用requests模块,是基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库

安装requests是模块

pip install requests

requests模块的使用

requests支持http的请求类型,如get,post,delete,put,head等

如:

r=requests.get("www.baidu.com")

r=requests.post("www.baidu.com")

也可以使用这个格式来处理所有的格式

requests.request(method, url, **kwargs)

传递参数

将参数定义为字典类型进行传递给params或者data

如,

para={"kw":"python"}

r=reuqests.get{"www.baidu.com",params=para}

字典中值为none的键值对不对传递过去,字典的值也可以为列表

响应结果

使用r.text获取到响应结果

json响应结果

使用r.json获取到json响应结果

二进制响应结果

使用r.content获取

定制head头

将定制的head定义为字典类型传递给headers即可

head={"content-type":"application/json"}

r.requests.get{'www.baidu.com',params=para,headers=head}

post一个多部分编码的文件(Multipart-Encoded)

url = 'http://httpbin.org/post'

files = {'file': open('report.xls', 'rb')}

r = requests.post(url, files=files)

如果你发送一个非常大的文件作为 multipart/form-data 请求,你可能希望流请求(?)。默认下 requests 不支持, 但有个第三方包支持 - requests-toolbelt.

安装

pip install requests-toolbelt

应用

from requests_toolbelt import MultipartEncoder

import requests

m = MultipartEncoder(

fields={'field0': 'value', 'field1': 'value',

'field2': ('filename', open('file.py', 'rb'), 'text/plain')}

)

r = requests.post('http://httpbin.org/post', data=m,

headers={'Content-Type': m.content_type})

响应吗

r.status_code

响应头

r.headers

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值