码迷,mamicode.com
首页 > Windows程序 > 详细

api_requests

时间:2020-07-07 19:22:05      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:orm   phone   str   day   not   rom   logger   content   headers   

#!/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

标签:orm   phone   str   day   not   rom   logger   content   headers   

原文地址:https://www.cnblogs.com/zhang-ping1205/p/13262605.html

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