api_requests

Posted Memory.荒年〆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了api_requests相关的知识,希望对你有一定的参考价值。

#!/user/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/7/7 15:32
# @Author :Test_zhangping
# @Email :981874735@qq.com
# @File :api_requests.py
import requests
import json

from Class_Request_API_接口自动化.class_day6.Common.my_logger import logger
from Class_Request_API_接口自动化.class_day6.Common.handle_config import conf

def api_requests(method,url,data=None,token=None):
"""

:param method: GET/POST/PUT/DELETE/HADE
:param url:
:param data: 字典形式的数据
:param token:
:return:
"""
logger.info("发起HTTP请求")
# 获取到请求头
headers = __api_header(token)
# 获取到完整的url -拼接url
url = __test_url(url)
# 请求数据的处理 -假如是字符串,转换为字典对象
data = __test_data(data)
# 将请求数据转换为字典对象
logger.info("请求头:{}".format(headers))
logger.info("请求方法:{}".format(method))
logger.info("请求url:{}".format(url))
logger.info("请求数据:{}".format(data))
# 根据请求的类型,调用请求方法
# method =[GET,POST,PUT,DELETE,HADE]
method = method.upper() # 请求方法大写
if method == "GET":
resp = requests.get(url, data, headers=headers)
elif method == "POST":
resp = requests.post(url, data, headers=headers)
elif method == "PUT":
resp = requests.put(url, data, headers=headers)
elif method == "DELETE":
resp = requests.delete(url, data, headers=headers)
else:
resp = requests.head(url, data, headers=headers)
logger.info("响应状态码:{}".format(resp.status_code))
logger.info("响应数据:{}".format(resp.json()))
return resp

def __api_header(token= None):
"""
请求头处理;项目中必带请求头header
如果有token,需要带上token
:param token: token值
:return: 处理之后的headers为字典格式
"""
headers = {"X-Lemonban-Media-Type": "lemonban.v2",
"Content-Type":"application/json"}
if token:
headers["Authorization"] ="Bearer {}".format(token)
return headers

def __test_url(url):
"""

:param url: 拼接接口url地址
:return:
"""
base_url = conf.get("server","base_url")
if url.startswith("/"):
return base_url + url
else:
return base_url +"/" + url

def __test_data(data):
"""

:param data: 如果是字符串;则转换成字典
:return:
"""
if data is not None and isinstance(data,str): # 判断data参数是否为支付传或者为空
return json.loads(data)# 转换为字典格式
return data # 返回data参数后续调用

if __name__ == ‘__main__‘:
login_url = "/member/login"
login_datas = {"mobile_phone": "18605671115", "pwd": "123456789"}
resp = api_requests("POST",login_url,login_datas)
# resp.content.decode("gbk")
# print(type(resp))
token = resp.json()["data"]["token_info"]["token"]
print(resp.json())

recharge_url = "/member/recharge"
recharge_data = {"member_id": 200713, "amount": 2000}
resp = api_requests("POST",recharge_url,recharge_data,token)
print(resp.json())

以上是关于api_requests的主要内容,如果未能解决你的问题,请参考以下文章