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