zoukankan      html  css  js  c++  java
  • 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

    运行结果:

              

  • 相关阅读:
    040 Android TCP协议的Socket通信
    039 Android SQLite数据库(了解)
    Navicat 连接Sqlite数据库的方法和步骤
    038 Android File文件存储功能
    037 Android SharedPreferences应用实例(记录App的使用次数)
    036 Android SharedPreferences(数据存储,需掌握)
    035 Android 广播(BroadCastReceiver)
    SharePoint2013打印列表项对象
    SharePoint2013所有列表绑定到DropDownList1中
    通过主机标头实现多个SharePoint Web应用程序共用一个端口(
  • 原文地址:https://www.cnblogs.com/zengxuejie/p/14276098.html
Copyright © 2011-2022 走看看