python 测试框架中的数据库连接类(mysql示例)
1.数据库信息yaml文件 conf_env.yaml
host:
doname: demo.pab.com.cn
port : 80
database:
host: "db.fat.qa.pab.com.cn"
user: "deploy"
password: "thess"
dbname: "testdb"
charset: "utf8"
2.与数据库yaml文件同级目录,创建配置config.py,内容如下
import os
project_dir = os.path.split(os.path.abspath(__file__))[0]
3.创建db_service.py, 内容如下
from cfg_service import get_db_connect_msg
import pymysql
import logging
logging.basicConfig(level=logging.DEBUG)
class dbService(object):
def __init__(self):
self.conn = self.connect()
#conn_str={'database': {'host': 'db.fat.qa.pab.com.cn', 'user': 'deploy', 'password': 'thess', 'dbname': 'testdb','charset': 'utf8'}}\
def connect(self, isyaml: bool = True, conn_str: dict = None):
if isyaml:
conn_str = get_db_connect_msg()
else:
conn_str = conn_str
try:
cursor = pymysql.connect(host=conn_str['database']['host'],
user=conn_str['database']['user'],
password=conn_str['database']['password'],
database=conn_str['database']['dbname'],
charset=conn_str['database']['charset']).cursor()
return cursor
except Exception as e:
raise e
def select(self, sql_str):
self.conn.execute(sql_str)
return self.conn.fetchall()
def __del__(self):
self.conn.close()
2.创建cfg_service.py,内容如下
import config
import os
import yaml
def get_db_connect_msg():
env_conf = os.path.join(config.project_dir, "conf_env.yml")
conn_str = ''
if os.path.exists(env_conf):
with open(env_conf, "r") as file:
yaml_cont = file.read()
conn_str = yaml.load(yaml_cont, Loader=yaml.FullLoader)
else:
raise FileNotFoundError
return conn_str
if __name__ == '__main__':
print(get_db_connect_msg())