封装的工具集(连接MySQL、redis,读写yaml\ini文件,接口发送请求,数据可视化)

目录

背景

目的

1,Mysql数据库连接

2,Redis内存数据库的连接

2,with open的封装

3,requests方法的封装

4、matplotlib数据可视化工具的封装



背景:

很多时候我们需要重复的使用某个代码块,如果说每次使用都写一遍的话,那就是重复造轮子了,没有必要,也使得代码很冗余,不方便做维护。所以我们需要把经常用到的代码块进行封装,使用的时候直接调用就好了,那样就可以节省很多的时间 


目的:

 节省代码开发时间,避免代码冗余,解耦合,利于代码的管理


1,Mysql数据库连接

前置条件:下载python编译器,pip install pymysql
简介:调用此类,则会读取数据库连接配置文件,使用pymysql进行连接数据库,并返回给调用方一个mysql数据库对象

from RequestUnittestDDT.util import operat_config

def getMysql():
    #read_yaml_all为自定义方法,可直接使用with open打开文件
    cfg = operat_config.read_yaml_all('config/mysql.yaml')
    mysql_host = cfg["mysql1"]["host"]
    mysql_user = cfg["mysql1"]["user"]
    mysql_password = cfg["mysql1"]["password"]
    mysql_port = cfg["mysql1"]["port"]
    mysql_db = cfg["mysql1"]["database"]
    mysql_charset = cfg["mysql1"]["charset"]
    mysql = pymysql.connect(host=mysql_host,
                                 user=mysql_user,
                                 password=mysql_password,
                                 port=mysql_port,
                                 db=mysql_db,
                                 charset=mysql_charset)
    return mysql
if __name__ == '__main__':
    getMysql()

以下为自定义的读取文件的方法: 

'''调用此方法可执行读取文件内容的操作,入参可谓相对路径也可为绝对路径'''
def read_yaml_all(file_path):
    try:
        yaml_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), file_path)
        with open(yaml_path, "r+", encoding="utf-8") as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
            return data
    except:
        return None


2,Redis内存数据库的连接
 

需要安装的模块为redis:  pip install redis

read_yaml_all方法和以上的方法一样

import redis
def getRedis():
    #read_yaml_all为自定义方法,可直接使用with open打开文件
    cfg = operat_config.read_yaml_all('config/redis.yaml')
    redis_host = cfg["redis1"]["host"]
    redis_password = cfg["redis1"]["password"]
    redis_port = cfg["redis1"]["port"]
    redis_db = cfg["redis1"]["database"]
    redis_decode = cfg["redis1"]["decode_responses"]
    rd = redis.Redis(host=redis_host,password=redis_password,
                    port=redis_port,db=redis_db,decode_responses=redis_decode)
    return rd
if __name__ == '__main__':
    getRedis()


2,读写yaml文件或读写ini文件

①yaml文件

import os
import ruamel.yaml
import yaml

'''此方法别的模块调用会报错,但是可复制到别的模块上使用'''
def read_yaml(file_path):
    with open(file_path,'r',encoding='utf-8') as f:
        file = yaml.load(f.read())
    return file
'''调用此方法可执行读取文件内容的操作,入参可是相对路径也可为绝对路径'''
# pip install ruamel_yaml
def read_yaml_all(file_path):
    try:
        yaml_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), file_path)
        with open(yaml_path, "r+", encoding="utf-8") as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
            return data
    except:
        return None

import ruamel.yaml
'''此方法可用户把数据写入yaml文件中'''
def createYaml(file,data:dict):
    with open(file,'w',encoding='utf-8') as f:
        create = ruamel.yaml.YAML()
        create.indent(mapping=2,sequence=4,offset=2)
        create.dump(data,f)

if __name__ == '__main__':
    #读
    print(read_yaml('../api/WebTours/login.yaml'))
    #写
    createYaml('data.yaml',{'staff1':[{'name':'江云'},{'age':18}],'staff2':[{'name':'婧祎'},{'age':18}]})

②ini文件 

'''此方法用于读取ini文件'''
import os
from configparser import ConfigParser
def readIni():
    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.ini")
    cf = ConfigParser()
    cf.read(file_path, encoding='utf-8')
    print(cf.sections())    #['User1', 'User2']
    print(cf.options('User1'))  #['username', 'password']
    print(cf.items('User1'))    #[('username', '江云'), ('password', '123456')]
    print(cf.get('User1', 'username'))  #江云
    print(cf.getint('User1', 'password'))  #123456

'''此方法用于将信息写入ini文件中'''
from configparser import ConfigParser
def createIni(selection,option,value,*args):
    config = ConfigParser()
    config.add_section(selection)
    config.set(selection,option,value)
    if(len(args)>=2):
        config.set(selection,args[0],args[1])
    if(len(args)>=4):
        config.set(selection,args[2],args[3])
    config.write(open("config.ini","a",encoding='utf-8'))
if __name__ == '__main__':    
    readIni() #读
    # createIni('User1','username','江云','password','123456') #写
    # createIni('User2','username','婧祎','password','654321')


3,requests方法的封装

简介:为了自己方便,有时候可以自己封装requests的方法,通过入参方法来判断具体的方法,然后发送相应的请求,使用**kwargs方便兼容需要加file参数和json参数,以及需要添加请求头的场景

#encoding='utf-8'
import requests
#此方法用于封装requests的请求
def session_send(session,method,url, **kwargs):
    if method == 'post' or method=='POST':
        response = session.post(url=url,**kwargs)
        return response
    elif method == 'get' or method=='GET':
        response = session.get(url=url,**kwargs)
        return response
if __name__ == '__main__':
    session = requests.session()
    response = session_send(session,'get','https://www.baidu.com/')
    print(response.status_code,response.text)

4、matplotlib数据可视化工具的封装

简介:可用于我们平时测试数据的可视化分析,如接口自动化测试中响应时间的数据可视化 
前置条件:下载好matplotlib2D绘图库模块,

pip install matplotlib

可配置的参数有
画布大小
折线的线大小
图表标题
坐标轴的标签名和线的大小
刻度标记的大小和线的大小
可视化图的种类,选plot就是折线图,选bar就是柱状图

 对应的python代码如下:

#pip install matplotlib
import matplotlib.pyplot as plt
'''此方法用于数据、测试数据的可视化'''
def visual_image(x,y):
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.rcParams['axes.unicode_minus'] = False  #解决因为中文导致乱码现象
    # 改变画布大小,目前是放大
    plt.figure(figsize = (30,8))
    plt.plot(x,y,linewidth = 2)##折线图
    #图表标题
    plt.title('接口响应时间折线图',fontsize = 24)
    #坐标轴的标签
    plt.xlabel('接口名称',fontsize = 14)
    plt.ylabel('响应时间',fontsize = 14)
    #设置刻度标记的大小
    plt.tick_params(axis='both',labelsize = 14)
    # plt.bar(x,y)##柱状图
    #打开matplotlib查看器,并绘制图像查看
    plt.show()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值