接口自動(dòng)化測(cè)試框架實(shí)戰(zhàn):日志和數(shù)據(jù)庫(kù)的封裝

今天完成兩部分的內(nèi)容,日志和數(shù)據(jù)庫(kù)的封裝。

log日志的封裝

import datetime
import logging
import os

from config import Conf
from config.Conf import ConfigYaml

log_l = {
    "info": logging.INFO,
    "debug": logging.DEBUG,
    "warning": logging.WARNING,
    "error": logging.ERROR

}

class Logger():
    def __init__(self, log_file, log_name, log_level):
        self.log_file = log_file
        self.log_name = log_name
        self.log_level = log_level
        #設(shè)置logger名稱(chēng)
        self.logger = logging.getLogger(self.log_name)
        self.logger.setLevel(log_l[self.log_level])
        formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
        if not self.logger.handlers:
            # 輸出到控制臺(tái)
            self.fh_stream = logging.StreamHandler()
            self.fh_stream.setLevel(log_l[self.log_level])
            self.fh_stream.setFormatter(formatter)
            self.logger.addHandler(self.fh_stream)
            #寫(xiě)入文件
            self.fh_file = logging.FileHandler(self.log_file)
            self.fh_file.setLevel(log_l[self.log_level])
            self.fh_file.setFormatter(formatter)
            self.logger.addHandler(self.fh_file)

#獲取日志文件存儲(chǔ)路徑
log_path = Conf.get_log_path()

current_time = datetime.datetime.now().strftime("%Y-%m-%d")

log_extension=ConfigYaml().get_conf_log_extension()

#日志文件名稱(chēng)
logfile=os.path.join(log_path,current_time+log_extension)

#獲取日志級(jí)別(放在配置文件里面,方便根據(jù)需求修改)
loglevel = ConfigYaml().get_conf_log()

def my_log(log_name=__file__):

    return Logger(log_file=logfile,log_name=log_name,log_level=loglevel).logger

if __name__ == '__main__':
    my_log().info('123456')

數(shù)據(jù)庫(kù)的封裝

import pymysql
from utils.LogUtil import my_log
class MySql():
    def __init__(self,host,user,password,database,charset,port):
        self.log = my_log('database')
        self.conn = pymysql.connect(
                    host=host,
                    user=user,
                    password=password,
                    database=database,
                    charset=charset,
                    port=port
                    )
        self.cursor=self.conn.cursor(pymysql.cursors.DictCursor)

    def fetchone(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchone()

    def fetchall(self, sql):
        """
        多個(gè)查詢(xún)
        """
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def exec(self, sql):
        """
        執(zhí)行
        """
        try:
            if self.conn and self.cursor:
                self.cursor.execute(sql)
                self.conn.commit()
        except Exception as ex:
            self.conn.rollback()
            self.log.error("Mysql 執(zhí)行失敗")
            self.log.error(ex)
            return False
        return True

        # 4、關(guān)閉對(duì)象

    def __del__(self):
        # 關(guān)閉光標(biāo)對(duì)象
        if self.cursor is not None:
            self.cursor.close()
        # 關(guān)閉連接對(duì)象
        if self.conn is not None:
            self.cursor.close()

if __name__ == "__main__":
    mysql = MySql("xxxxxxx",
                  "test",
                  "test123456","xxxxxx",
                  charset="utf8",
                  port=7090)
    res = mysql.fetchall("select username,password from tb_users")
    # res = mysql.exec("update tb_users set first_name='python' where username = 'python'")
    print('1111',res)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容