Python常用配置文件读取方法

常见的应用配置方式有环境变量和配置文件,对于微服务应用,还会从配置中心加载配置,比如nacos、etcd等,有的应用还会把部分配置写在数据库中。此处主要记录从环境变量、.env文件、.ini文件、.yaml文件、.toml文件、.json文件读取配置。

ini文件

ini文件格式一般如下:

[mysql]
type = "mysql"
host = "127.0.0.1"
port = 3306
username = "root"
password = "123456"
dbname = "test"

[redis]
host = "127.0.0.1"
port = 6379
password = "123456"
db = "5"

使用python标准库中的configparser可以读取ini文件。

import configparser
import os

def read_ini(filename: str = "conf/app.ini"):
    """
    Read configuration from ini file.
    :param filename: filename of the ini file
    """
    config = configparser.ConfigParser()
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    config.read(filename, encoding="utf-8")
    return config

config类型为configparser.ConfigParser,可以使用如下方式读取

config = read_ini("conf/app.ini")

for section in config.sections():
    for k,v in config.items(section):
        print(f"{section}.{k}: {v}")

读取输出示例

mysql.type: "mysql"
mysql.host: "127.0.0.1"
mysql.port: 3306
mysql.username: "root"
mysql.password: "123456"
mysql.dbname: "test"
redis.host: "127.0.0.1"
redis.port: 6379
redis.password: "123456"
redis.db: "5"

yaml文件

yaml文件内容示例如下:

database:
  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"
  maxsize: 100
  maxage: 30
  maxbackups: 30
  compress: true

读取yaml文件需要安装pyyaml

pip install pyyaml

读取yaml文件的示例代码

import yaml
import os

def read_yaml(filename: str = "conf/app.yaml"):
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    with open(filename, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f.read())
        return
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

!chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值