requests库

一,GET请求

1. GET方法:
 作用:获取资源(查询)
 步骤:
1. 导包:import requests
2. 调用get方法:r=requests.get() #r:响应对象
3. 获取响应对象
  •  获取url:响应对象.url
  •  获取响应状态码:响应对象.status_code
  • 获取响应信息:响应对象.text

例一;

import requests
# 访问一个url接口地址,发送一个get请求
url = "https://api.github.com"
res = requests.get(url)
print(res)   # <Response [200]>  响应对象
print(res.text) #查看响应正文--文本格式
print(res.status_code) #查看响应码
print(res.url)
#统一格式就不会再出现乱码
res.encoding='utf-8'
print(res.text) #查看响应正文--文本格式
print('请求编码格式',res.encoding)  #ISO-8859-1

例二:GET请求带参数

# 如何传递参数,如何修改请求头:token
headers = {"token":"123","username":"mingxing"}
url = "http://api.github.com"
# res = requests.get(url,headers)

# 如何传递参数,位置参数,或者关键字参数params,通过?链接
data = {"username":"mingxing","pwd":"123456"}
res = requests.get(url,params=data,headers=headers)
print(res)

二,POST请求

POST方法:
作用:提交资源、新增资源
 步骤:
  1. 导包:import requests
  2. 参数:
    1. url:接口地址
    2. json:请求参数
    3. Header:请求头信息
  3. 调用post方法:r=requests.post(url,json,headers) #r:响应对象
4. 获取响应对象
  响应状态码:响应对象.status_code
  响应信息:响应对象.json() #以json格式查看响应内容

2.1,请求对象

# 发送post请求
url = "http://127.0.0.1:5000/login"
requests.post(url)
# 如何发送header请求
headers = {"dalao":"cai","usernaem":'xingxing'}
requests.post(url,headers=headers)

 post请求参数传递

1,以query_string形式传递

# params,就是以query_string形式传递。
data = {"usernam":"weiwei","admin":"hahaha"}
headers = {"dalao":"cai","usernaem":'xingxing'}
res  = requests.post(url,headers=headers,params = data)

 2,以表单形式

# 传递参数2:表单形式
form_data = {"form_admin":"niuniu"}
res = requests.post(url,data=form_data,headers=headers,params = data)

 3,以json格式传递

# 传递参数3:json
json_data = {"json_data":"123"}
res  = requests.post(url,json=form_data,headers=headers,params = data)

 注意:不能json和data两者都传,虽然不报错,但之后接收表单格式的

2.2,响应对象

url = "http://127.0.0.1:5000/login"
json_data = {"json_data":"123"}
jsonres  = requests.post(url,json=form_data,headers=headers,params = data)
# 获取相应文本,得到的数据类型,string
print(jsonres.text)
# 获取二进制形式
print(jsonres.content)
# json ,不是 json 的相应数据
# json 得到的是字典类型
print(jsonres.json())

2.3 实战

import requests
# 注册接口
# 准备访问接口URL
url = "http://120.78.128.25:8766/futureloan/member/register"

# 没有准备headers:"msg":"请求头X-Lemonban-Media-Type不存在"
res = requests.post(url)
print(res.text)
print(res.json())

# 准备headers
headers = {"X-Lemonban-Media-Type":"lemonban.v1"}
data = {"mobile_phone":"18111111119","pwd":"12345678"}
# 一定要添加headers关键字参数,不能以位置参数传递
# 因为放到了可变长参数里面
# content-type不需要添加,为什么?json关键字参数就是表示content-type =json,
# data关键字参数就是表示,表单格式,
# params参数就是表示 query_string
res = requests.post(url,json=data,headers=headers)
print(res.json())
requests之header传递
# 登录接口
# token 放在什么地方
# token 可以放到请求体中,?? 根据接口文档,只是一种协议,开发人员和你之间定义的协议
# cookie 可以放到请求体中? HTTP协议
url = "http://120.78.128.25:8766/futureloan/member/login"
headers = {"X-Lemonban-Media-Type":"lemonban.v2"}
data = {"mobile_phone":"18111111119","pwd":"12345678"}
res = requests.post(url=url,json=data,headers= headers)
print("aaaaa",res.json())

# 如果我要访问其他的接口
# 充值
recharge_url = "http://120.78.128.25:8766/futureloan/member/recharge"
# 获取登录接口的token
token = res.json()["data"]["token_info"]["token"]
# 获取登录接口的id
id = res.json()["data"]["id"]
headers = {"X-Lemonban-Media-Type":"lemonban.v2","Authorization":"Bearer {0}".format(token)}
data = {
    "member_id":id,
    "amount":100
}
res = requests.post(url=recharge_url,json=data,headers=headers)
print("充值的结果为:",res.json())
requests之token获取
# 一,如何操作cookie?
# 登录:
login_url = "http://test.lemonban.com/futureloan/mvc/api/member/login"
data = {"mobilephone": "18211111111","pwd": "123456"}
res = requests.get(login_url, data)
print(res.json())

# 获取cookie
cookies = res.cookies

# 充值
recharge_url = "http://test.lemonban.com/futureloan/mvc/api/member/recharge"
recharge_data = {"mobilephone": "18211111111", "amount": "1000"}
res = requests.post(recharge_url, data=recharge_data, cookies=cookies)
print(res.text)
requests之操作cookie
# 二,session操作
# 登录
# 创建一个session对象,自动携带cookies
session = requests.Session() # 相当于开启了一个浏览器
login_url = "http://test.lemonban.com/futureloan/mvc/api/member/login"
data = {
    "mobilephone": "18211111111",
    "pwd": "123456"
}
res = session.post(login_url, data)
print(res.json())
# 充值
recharge_url = "http://test.lemonban.com/futureloan/mvc/api/member/recharge"
recharge_data = {"mobilephone": "18211111111", "amount": "1000"}
res = session.post(recharge_url, data=recharge_data)
print(res.text)
session.close()

# 初始化另外一个session
# 就需要先登录
session_another = requests.Session()  # 新打开一个会话
res = session_another.post(recharge_url, data=recharge_data)
print(res.text)   # {"status":0,"code":null,"data":null,"msg":"抱歉,请先登录。"}
requests之操作session

 三,request请求封装

# 封装
import requests
class HttpHandler:
    def __init__(self):
        self.session = requests.Session()

    def visit(self,url, method,params=None,data = None, json=None,**kwargs):
        '''
        访问一个接口,你可以使用get请求,也可以使用post请求,put,delete请求等
        请求方法:method
        请求地址:url
        请求参数:params,data,json
        :return:
        '''
        # if method.lower() == 'get':
        #     res = self.session.get(url=url,params=params,**kwargs)
        # elif method.lower() =='post':
        #     res = self.session.get(url=url, params=params, data=data, json=json, **kwargs)
        # else:
            # 可以处理请求方法。
        res = self.session.request(method=method, url=url,params=params, data=data, json=json,**kwargs)
        try:
            return res.json()
        except ValueError:
            print("not json")

 

posted @ 2020-11-11 07:19  勇敢面对difficult  阅读(103)  评论(0)    收藏  举报