Python项目如何管理配置?有哪些最佳实践?
中等Python
答题要点
# 环境变量
import os
DATABASE_URL = os.environ.get('DATABASE_URL', 'localhost:5432')
# python-dotenv
from dotenv import load_dotenv
load_dotenv() # 加载.env文件
# Pydantic Settings(推荐)
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
redis_url: str = 'redis://localhost'
debug: bool = False
api_keys: list[str] = []
class Config:
env_file = '.env'
env_file_encoding = 'utf-8'
settings = Settings()
# YAML配置
import yaml
def load_config(path: str) -> dict:
with open(path) as f:
return yaml.safe_load(f)
# 分环境配置
class DevSettings(Settings):
debug: bool = True
class ProdSettings(Settings):
debug: bool = False
def get_settings():
env = os.getenv('ENV', 'dev')
return DevSettings() if env == 'dev' else ProdSettings()
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题