Python接口自动化基础

学习链接:http://docs.python-requests.org/zh_CN/latest/user/advanced.html

https://www.cnblogs.com/ranxf/p/7808537.htmls

post请求:

常见的post传递参数的类型有以下两种:

第一种:application/x-www-form-urlencoded,浏览器原生的form表单,格式如下input1=xxx&input2=ooo

第二种:application/json,常见的json格式,格式为{“input”:‘xx’,'input2':'ooo'},一般APP端都是用第二种

1、以表单形式传递参数,只需简单的传递一个字典给data关键字,在发送的请求的时候,会自动编码为表单的形式

import requests
param1={'username':'test','password':'123456'}
r1=requests.post('http://127.0.0.1/login',data=param1)
print r1.text
print r1.status_code

2、以json格式传递参数

url是https时,访问不同,如果是http,则访问通

想要在post请求中使用data关键字来传递json格式的字符串,首先把dict转换为string

#以json格式传递参数
url='xxxxx'
data={'phoneNumber':'pCp0umKb/1eBu99Da tnQ4lZullWTCoCVvvyhhzdDDyOgPJ9CpTFu1Z0xgFqnw3CzkWnutc8WeYjVo4/iJsvnnB4EdudytrHRNpkpzMPZ Ahqz vySOusfWPocXEwW5iX5i/hMO7z5enr94T1k8ynnR3 SGtX4pt8QC/okkEMtw=','type':1,'channel':1,'statistics':'iOS|AppStore|1.0|0C768FA3-C685-48CB-8779-F72A5AC6DB61|iPhone|no|no|wifi|3.9.7',
      'echoStr':'5B92DF98C900AA39B6B398E43922AB72','packageName':'cxx',
      'sign':'8557656034D8242F91FED16F115D90AA','time':'2018-10-16 15:15:33'}
json_data=json.dumps(data)
print json_data
r=requests.post(url,data=json_data) #第一种方式,转换成string
r=requests.post(url,json=data) #第二种方式,直接使用json关键字传递
print r.text
print r.status_code

2、get请求

r=requests.get('https://www.python.org')
print r.text
print r.status_code

3、header请求头

请求头写成字典的格式

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
            "Accept-Encoding": "gzip, deflate, br",
            "Content-Type": "application/json; charset=utf-8",
            "X-Requested-With": "XMLHttpRequest",
            "Cookie": "xxx.............",    # 此处cookie省略了
            "Connection": "keep-alive"
            }

 

request发送请求:https://developer.github.com/

get:查看资源

post:增加资源

put:修改资源

delete:删除资源

options:查看可用请求方法

 

# -*- coding=utf-8 -*-
# author=zyq
import requests
import  json
from io import StringIO
#import StringIO #用于在内存缓存区中读写数据


'''param1={'username':'test','password':'123456'}
r1=requests.post('http://127.0.0.1/login',data=param1)
print r1.text
print r1.status_code'''


#以json格式传递参数
'''url='http://qc-api.jianlc.com/app/v5/sendAuthCode?'
data={'phoneNumber':'pCp0umKb/1eBu99Da tnQ4lZullWTCoCVvvyhhzdDDyOgPJ9CpTFu1Z0xgFqnw3CzkWnutc8WeYjVo4/iJsvnnB4EdudytrHRNpkpzMPZ Ahqz vySOusfWPocXEwW5iX5i/hMO7z5enr94T1k8ynnR3 SGtX4pt8QC/okkEMtw=','type':1,'channel':1,'statistics':'iOS|AppStore|1.0|0C768FA3-C685-48CB-8779-F72A5AC6DB61|iPhone|no|no|wifi|3.9.7',
      'echoStr':'5B92DF98C900AA39B6B398E43922AB72','packageName':'com.jianlcvip.simplefinance.3.9.8',
      'sign':'8557656034D8242F91FED16F115D90AA','time':'2018-10-16 15:15:33'}
json_data=json.dumps(data)
print json_data
r=requests.post(url,data=json_data) #第一种方式,转换成string
r=requests.post(url,json=data) #第二种方式,直接使用json关键字传递
print r.text
print r.status_code'''

'''r=requests.get('https://www.python.org')
print r.text
print r.status_code'''

'''s=StringIO()
s.write("www.baidu.com")
print s.read()
s.write("news.realsil.com.cn")
print s.getvalue()  #用于读取写入后的str'''

'''import  gzip
g=gzip.GzipFile(filename="",mode='wb',fileobj="") #压缩文件
g.write()
g.close()

g=gzip.GzipFile(filename="",mode='rb',fileobj="")# 解压文件
open()'''

r=requests.get('https://api.github.com/events') #r是response的对象,可以从对象中获取想要的信息
#print r.status_code
#print r.content
#print r.text

r=requests.post('http://httpbin.org/post',data={'key':'value'})

#get传参的方式
url='http://httpbin.org/get'
data={'key':'value'}
r=requests.get(url,params=data)
#print r.url  #获取get带参数的路径

#可以将一个列表作为值传入
payload={'key1':'value1','key2':['value2','value3']}
r=requests.get(url,params=payload)
#print r.url

#响应内容
r=requests.get('https://api.github.com/events')
#print r.text
#print r.encoding
r.encoding='ISO-8859-1' #重新设置编码格式
#print r.text
#print  r.content   #对于非文本请求,二进制的响应内容时,用r.content,requests会自动为你解码gzip和deflate传输编码的响应数据

#json 响应内容,成功调用r.json,并不意味着响应成功,可以检查r.status_code是否和期望的相同
#print r.json()  #返回json数据

#原始响应内容,获取来自服务器的原始套接字响应,确保请求中设置了stream=True
r=requests.get('https://api.github.com/events',stream=True)
#print r.raw



#定制请求头,传递一个dict给headers参数,header的值必须是string,bytestring或者unicode
url='https://api.github.com/some/endpoint'
headers={'user-agent':'my-app/0.0.1'}
r=requests.get(url,headers=headers)

#更加复杂的post请求
payload={'key1':'value1','key2':'value2'}
r=requests.post('http://httpbin.org/post',data=payload)
#print r.text


#响应状态码
print r.status_code #获取状态码
print r.status_code==requests.codes.ok  #状态码查询对象和获取的状态码是否一致

#响应头
print r.headers
#可以使用任意大写形式来访问这些响应头字段
print r.headers['Content-Length']

#cookie
url='http://example.com/some/cookie/setting/url'
r=requests.get(url)
print r.cookies

#发送cookies到服务器,可以使用cookies参数
url='http://httpbin.org/cookies'
cookies=dict(cookies_are='working')
r=requests.get(url,cookies=cookies)
print r.text


#重定向
r=requests.get('http://github.com')  #重定向了https://github.com
print r.url
print r.status_code
print r.history

#可以使用参数allow_redirects参数禁用重定向处理
r=requests.get('http://github.com',allow_redirects=False)  #禁用重定向,返回为http的形式
print r.url
print r.status_code

#超时,可以使用参数timeout=xx设定秒数时候之后停止等待响应
#timeout仅对链接过程有效,对响应体的下载无关,timeout是服务器在该秒内没有应答,将会引发一个异常
print requests.get('http://github.com',timeout=0.01)

#错误与异常
#遇到网络问题时,会抛出一个connectionError异常
#如果http请求返回了不成功的状态码,response.raise_for_status() 会抛出一个httpERROR异常
#请求超时,会抛出一个timeout异常
#若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
#所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。
# -*- coding=utf-8 -*-
# author=zyq
import requests
#会话对象
#会话对象让你能够跨请求保持某些参数,他会在同一个session实例发出的所有请求直接保持cookie

#跨请求保持一些cookie
s=requests.session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r=s.get("http://httpbin.org/cookies")
#print r.text

#请求与响应对象
'''任何时候进行了类似requests.get()调用,在做两件事,一,在构建一个request对象,改对象将被发送到某个服务器请求或查询
一些资源,二,一旦request得到一个从服务器返回的响应就会产生一个response对象,改响应对象包含服务器返回的所有信息,也包含你原来创建的request对象'''
r=requests.get('http://httpbin.org/cookies')
#print r.headers  #获取头部信息
r.request.headers  #发送到服务器的请求头部


#ssl证书验证,如果证书验证失败,会抛出sslError
requests.get("https://requestb.in",verify=True)

#verify=False,请求忽略对ssl证书的验证,默认情况下为True
requests.post('https://qc-api.jianlc.com/app/v5/sendAuthCode',verify=False)

#客户端证书
#可以指定一个本地证书用作客户端证书,可以是单个文件,包含密钥和证书,或者一个包含两个文件路径的元组
print requests.get('https://kennethreizt.org',cert=('/path/client.cert', '/path/client.key'))

#响应体内容工作流
#默认情况下,当你进行网络请求后,响应体会立即被下载,可以通过stream参数=true,推迟下载响应体直到访问r.contenr
with requests.get('http://httpbin.org/get',stream=True) as r:
    # 在此处理响应


#保持持久连接
#只有所有的响应体数据被读取完毕连接才会被释放为连接池;所以确保将stream设置为False或读取Response对象的content属性。

#流式上传
#requests支持流式上传,允许发送打的数据流或文件,而无需先把他们读入内存,用二进制模式打开文件
with open('test.cc','rb+') as f:
    requests.post('http://some.url/streamed',data=f)

#快编码请求
'''对于出去和进来的请求,Requests 也支持分块传输编码。要发送一个块编码的请求,仅需为你的请求体提供一个生成器(或任意没有具体长度的迭代器):'''
def gen():
    yield 'hi'
    yield 'there'
requests.post('http://some.url/chunked',data=gen())

 

 

转载于:https://my.oschina.net/u/3950843/blog/2247007

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值