python获取数据库配置_使用python读取配置文件并从mysql数据库中获取数据进行传参(基于Httprunner)...

最近在使用httprunner进行接口测试,在传参时,用到了三种方法:(1)从csv文件中获取;(2)在config中声名然后进行引用;(3)从函数中获取。在测试过程中,往往有些参数是需要从数据库中获取的,然后考虑到Httprunner提供的debugtalk.py插件,决定试试编写一个从数据库读取值的方法,在经过调试后,最后终于成功了,今天在这里记录下。

连接mysql数据库使用的是python的MySQLdb库,读取配置文件使用的是configparser库。debugtalk.py同级目录下包含文件有:

(1)mysqlDB.py

(2)readConfig.py

(3)config.ini

分别内容如下

一、配置文件config.ini内容如下:

[Mysql]

user_id= select id from user where name="root"[DATABASE]

host=x.x.x.x

user=test

passwd= 123456port= 3306database= rbac

二、readConfig.py(读取config.ini)

importosimportcodecsimportconfigparser

proDir= os.path.split(os.path.realpath(__file__))[0]

configPath= os.path.join(proDir, "config.ini")printconfigPathclassReadConfig:def __init__(self):

fd=open(configPath)

data=fd.read()#remove BOM

if data[:3] ==codecs.BOM_UTF8:

data= data[3:]

file= codecs.open(configPath, "w")

file.write(data)

file.close()

fd.close()

self.cf=configparser.ConfigParser()

self.cf.read(configPath)defMysql(self, name):

value= self.cf.get("Mysql", name)returnvaluedefDatabase(self, name):

value= self.cf.get("DATABASE", name)return value

三、mysqlDB.py

#-*- coding:utf-8 -*-

importMySQLdbfrom readConfig importReadConfig

mysql=ReadConfig()#db = MySQLdb.connect(host,user,passwd,database,charset="utf8")

classMysqlDb:def __init__(self):

self.host= mysql.Database("host")

self.user= mysql.Database("user")

self.passwd= mysql.Database("passwd")

self.database= mysql.Database("database")

self.db= MySQLdb.connect(self.host,self.user,self.passwd,self.database,charset="utf8")defuser_id(self):

cursor=self.db.cursor()

sql= mysql.Mysql("user_id")

cursor.execute(sql)#db.commit()提交到数据库执行

data = cursor.fetchone() #cursor

return data

四、debugtalk.py(提供给httprunnertest函数)

#-*- coding:utf-8

from mysqlDB importMysqlDb

test=MysqlDb()defUserId():

User_Id=test.user_id()return int(User_Id[0])

五.在test.yml中引用

-config:

name:'dashboard'request:

variables:- user_id: ${UserId()}

然后就可以跑test脚本了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值