#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2023/6/22 19:58 # @Author : old tom # @File : db_config.py # @Project : futool-db-lite # @Desc : import os from pydantic import BaseModel import toml # 默认配置文件名 DEFAULT_CONF_NAME = 'db-conf.toml' path = os.path.dirname(__file__) path = os.path.dirname(path) # 默认配置文件位置 DEFAULT_CONF_PATH = os.path.join(path, DEFAULT_CONF_NAME) # 配置项名称 DB_CONF_ITEM_NAME = ['dialect', 'host', 'port', 'user', 'passwd', 'database'] class DbConfigNotFoundError(Exception): """ 配置不存在异常 """ def __init__(self, msg): Exception.__init__(self, msg) class DbConf(BaseModel): dialect: str host: str port: int user: str passwd: str database: str pool_size: int pool_recycle: int show_sql: bool = False class DbConfigLoader(object): """ 数据库连接加载 """ def __init__(self, db_name, conf_path): if not os.path.isfile(conf_path): raise DbConfigNotFoundError(f'数据配置文件{DEFAULT_CONF_NAME}不存在') self.db_conf = self.load(db_name, conf_path) @staticmethod def load(dbname, conf_path) -> DbConf: """ 校验并加载配置 :return: """ conf = toml.load(conf_path) return DbConf(**conf[dbname])