码迷,mamicode.com
首页 > 编程语言 > 详细

python的requests模块

时间:2017-06-06 18:46:18      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:multipart   get   pos   .json   form   apach   report   text   status   

使用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")

传递参数

将参数定义为字典类型进行传递给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

 

python的requests模块

标签:multipart   get   pos   .json   form   apach   report   text   status   

原文地址:http://www.cnblogs.com/hellowcf/p/6952497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!