python读取配置文件的几种方式

下面只演示toml格式的,其他方式的就配置文件不一样

conf.toml

[database]
dbtype = "mysql"
 
[database.mysql]
host = "127.0.0.1"
port = 3306
user = "root"
password = "123456"
dbname = "test"
 
[database.redis]
host = ["192.168.0.10", "192.168.0.11"]
port = 6379
password = "123456"
db = "5"
 
[log]
directory = "logs"
level = "debug"

pkg/init.py文件为空,pkg/config.py内容如下:

import configparser
import os
import yaml
import toml
import json
import abc
from dotenv import load_dotenv


class Configer(metaclass=abc.ABCMeta):
    def __init__(self, filename: str):
        self.filename = filename

    @abc.abstractmethod
    def load(self):
        raise NotImplementedError(f"subclass must implement this method")

    def file_exists(self):
        if not os.path.exists(self.filename):
            raise FileNotFoundError(f"File {self.filename} not found")


class IniParser(Configer):
    def __init__(self, filename: str):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        config = configparser.ConfigParser()
        config.read(self.filename, encoding="utf-8")
        return config


class YamlParser(Configer):
    def __init__(self, filename: str):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        with open(self.filename, "r", encoding="utf-8") as f:
            config = yaml.safe_load(f.read())
            return config


class TomlParser(Configer):
    def __init__(self, filename: str):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        with open(self.filename, "rb") as f:
            config = toml.load(f)
            return config


class JsonParser(Configer):
    def __init__(self, cfgtype: str, filename: str = None):
        super().__init__(cfgtype, filename)

    def load(self):
        super().file_exists()
        with open(self.filename, "r", encoding="utf-8") as f:
            config = json.load(f)
            return config


class DotenvParser(Configer):
    def __init__(self, filename: str = None):
        super().__init__(filename)

    def load(self):
        super().file_exists()
        load_dotenv(self.filename, override=True)
        config = dict(os.environ)
        return config

main.py

from pkg.config import TomlParser
 
config = TomlParser("conf.toml")
print(config.load())

输出字典

{'database': {'dbtype': 'mysql', 'mysql': {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': '123456', 'dbname': 'test'}, 'redis': {'host': ['192.168.0.10', '192.168.0.11'], 'port': 6379, 'password': '123456', 'db': '5'}}, 'log': {'directory': 'logs', 'level': 'debug'}}
posted @ 2024-11-12 14:35  朝阳1  阅读(4)  评论(0编辑  收藏  举报