configparser优雅载入配置文件

112 阅读1分钟

configparser优雅载入配置文件

configparser 是 Python 中用于读取和编写配置文件的内置模块。它可以解析和操作 INI 格式的配置文件,这些配置文件通常用于存储程序的配置信息。

为什么使用configparser?

我们的项目中肯定会有数据库密码、各种apikey,我们会在不同地方反复多次调用,我们需要找一个地方统一维护这些敏感信息,configparser就可以解决这个问题。如果我们把这些文件推入gitlab上是非常危险的,我们需要结合.gitignore来过滤掉真正的配置文件,只把示例配置上传至git仓库,这是一个推荐的做法。

config.ini

[DEFAULT]
ServerAliveInterval = 45
Compression = yes

[db]
User = hg
Port = 50022

使用

from configparser import ConfigParser

CONFIG = ConfigParser()
CONFIG.read(str(BASE_DIR / "config.ini"))

# 读取 DEFAULT 部分的值
server_alive_interval = CONFIG.getint('DEFAULT', 'ServerAliveInterval')
compression = CONFIG.getboolean('DEFAULT', 'Compression')

# 读取 db 部分的值
db_user = CONFIG.get('db', 'User')

# 在别的文件中获取django的配置
from django.conf import settings
CONFIG = settings.CONFIG

config 方法

  • config.sections() 得到所有的section,并以列表的形式返回
  • config.options(section) 得到该section的所有option
  • config.items(section) 得到该section的所有键值对
  • config[section][option] 读取section中的option的值
  • config.get(section,option) 得到section中option的值,返回为string类型
  • config.getint(section,option) 得到section中option的值,返回为int类型
  • config.getboolean(section,option) 得到section中option的值,返回为bool类型
  • config.getfloat(section,option) 得到section中option的值,返回为float类型