Python项目中添加环境配置文件
在Python项目中添加配置文件有多种方式,每种方式对应不同的依赖包和读取方法。以下是 7种主流配置管理方案,包含安装命令、配置示例和变量读取方法:
1. .env
文件(推荐简单项目)
依赖包: python-dotenv
pip install python-dotenv
.env
文件内容:
DEBUG=true
API_KEY=your_key
DB_HOST=localhost
读取方式:
from dotenv import load_dotenv
import osload_dotenv() # 默认加载当前目录下的.env文件debug_mode = os.getenv("DEBUG") # 返回字符串
db_host = os.getenv("DB_HOST", "127.0.0.1") # 带默认值
2. JSON/YAML 配置文件
依赖包: 无需安装(标准库)或 pyyaml
pip install pyyaml # 仅YAML需要
config.json
:
{"database": {"host": "localhost","port": 5432}
}
读取方式:
import jsonwith open('config.json') as f:config = json.load(f)db_host = config["database"]["host"]
3. INI 格式(传统Windows风格)
依赖包: 标准库 configparser
config.ini
:
[database]
host = localhost
port = 5432
读取方式:
from configparser import ConfigParserconfig = ConfigParser()
config.read('config.ini')db_port = config.getint('database', 'port') # 自动转换类型
4. TOML 格式(Python生态新宠)
依赖包: toml
或 tomli
pip install toml
config.toml
:
[database]
host = "localhost"
ports = [8000, 8001]
读取方式:
import tomlwith open("config.toml", "r") as f:config = toml.load(f)ports = config["database"]["ports"]
5. 环境变量直接管理(生产环境推荐)
无需配置文件,直接在系统或容器中设置变量:
# Linux/Mac
export DB_HOST=localhost# Windows
set DB_HOST=localhost
读取方式:
import osdb_host = os.environ["DB_HOST"] # 直接读取系统变量
6. Pydantic 配置模型(类型安全推荐)
依赖包: pydantic
+ python-dotenv
pip install pydantic python-dotenv
.env
文件:
DB_HOST=localhost
读取方式:
from pydantic import BaseSettingsclass Settings(BaseSettings):db_host: strdb_port: int = 5432 # 默认值class Config:env_file = ".env"settings = Settings()
print(settings.db_host) # 自动类型转换
7. 动态热加载配置(高级场景)
依赖包: watchdog
+ pyyaml
pip install watchdog pyyaml
config.yaml
:
app:refresh_interval: 60
动态监听文件变化:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import yamlclass ConfigHandler(FileSystemEventHandler):def on_modified(self, event):if event.src_path.endswith('config.yaml'):with open(event.src_path) as f:global configconfig = yaml.safe_load(f)observer = Observer()
observer.schedule(ConfigHandler(), path='.')
observer.start()
方案对比总结
方案 | 适合场景 | 类型安全 | 动态更新 | 复杂度 |
---|---|---|---|---|
.env | 简单项目/开发环境 | ❌ | ❌ | ⭐ |
JSON/YAML | 结构化配置 | ❌ | ✅ | ⭐⭐ |
INI | 传统Windows应用 | ❌ | ✅ | ⭐ |
TOML | 现代Python项目 | ✅ | ✅ | ⭐⭐ |
环境变量 | 生产环境/容器化 | ❌ | ✅ | ⭐ |
Pydantic | 需要类型验证的项目 | ✅ | ❌ | ⭐⭐ |
动态加载 | 需要运行时修改配置 | ❌ | ✅ | ⭐⭐⭐ |
最佳实践选择
- 开发环境:
.env
+python-dotenv
- 生产环境:环境变量 + Pydantic验证
- 复杂配置:TOML/YAML + Pydantic模型
- 动态需求:Watchdog监听 + YAML
💡 安全提示:敏感信息(如密码/API密钥)永远不要提交到版本库,应通过环境变量或密钥管理服务传递。