zengxuejie

导航

Python接口自动化测试(18):Django数据初始化

封装数据

数据初始化主要包括:数据连接,数据清除,数据插入,关闭数据库,在api项目下新建一个目录test_project然后创建文件:mysql_action.py

# Author xuejie zeng
# encoding utf-8

from pymysql import  connect
import yaml

class DB():
    def __init__(self):
        """连接数据库"""
        print('connect db')
        self.conn = connect(host='127.0.0.1',port= 3307,user='root',password='123456',db='django_restful')

    def clear(self,table_name):
        """清除表中数据"""
        print("clear db")
        clear_sql = 'truncate ' + table_name + ';'

        with self.conn.cursor() as cursor:
            #清除外键约束
            cursor.execute("set foreign_key_checks=0;")
            cursor.execute(clear_sql)
        self.conn.commit()

    def insert(self,table_name,table_data):
        """插入数据"""
        print('insert db ...')
        #遍历数据
        for key in table_data:
            table_data[key] = "'" + str(table_data[key]) + "'"
        key = ','.join(table_data.keys())
        value = ','.join(table_data.values())
        print(key)
        print(value)

        insert_sql = "insert into " + table_name + "("  + key + ") " + "values" + "(" + value + " )"
        print(insert_sql)

        with self.conn.cursor() as cursor:
            cursor.execute(insert_sql)
        self.conn.commit()

    def close(self):
     """关闭数据库"""
print('close db ...') self.conn.close() def init_data(self,datas): """初始化数据""" print('init db ....') for table,data in datas.items(): self.clear(table) for d in data: self.insert(table,d) self.close() if __name__=='__main__': db=DB() with open('datas.yaml','r') as f: datas=yaml.load(f) db.init_data(datas)

数据分离

继续在test_project下创建datas.yaml文件

api_user:
  - id: 1
    username: test01
    email: 1234@qq.com
    groups: http://127.0.0.1:8000/groups/1/

  - id: 2
    username: test02
    email: 1234@qq.com
    groups: http://127.0.0.1:8000/groups/2/

api_groups:
  - id: 1
    name: dev

  - id: 2
    name: test

运行结果:

          

 

posted on 2021-01-14 14:36  曾小懒  阅读(450)  评论(0编辑  收藏  举报