生产环境配置:环境变量与安全管理
前言
安全的配置管理是生产环境的基础。本文介绍环境变量和敏感信息的最佳实践。
适合读者: 运维工程师、后端开发者
一、环境变量配置
# config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# 数据库配置
DATABASE_URL: str
# Redis配置
REDIS_URL: str = "redis://localhost:6379/0"
# JWT配置
SECRET_KEY: str
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
# Agent配置
AGENT_URL: str = "http://localhost:8001"
# Ollama配置
OLLAMA_BASE_URL: str = "http://localhost:11434"
# Weaviate配置
WEAVIATE_URL: str = "http://localhost:8080"
class Config:
env_file = ".env"
case_sensitive = True
settings = Settings()
二、.env文件
# .env
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/aiagent
REDIS_URL=redis://localhost:6379/0
SECRET_KEY=your-secret-key-change-in-production
AGENT_URL=http://localhost:8001
OLLAMA_BASE_URL=http://localhost:11434
WEAVIATE_URL=http://localhost:8080
三、敏感信息管理
# .env.example(提交到Git)
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/aiagent
REDIS_URL=redis://localhost:6379/0
SECRET_KEY=change-me
AGENT_URL=http://localhost:8001
# .gitignore
.env
.env.local
.env.production
四、生产环境配置
# 区分环境
class Settings(BaseSettings):
ENVIRONMENT: str = "development"
DEBUG: bool = False
@property
def is_production(self) -> bool:
return self.ENVIRONMENT == "production"
@property
def is_development(self) -> bool:
return self.ENVIRONMENT == "development"
# 使用
if settings.is_production:
# 生产环境配置
logger.add("logs/prod.log", level="INFO")
else:
# 开发环境配置
logger.add(sys.stdout, level="DEBUG")
下一篇预告: 《性能优化:从响应时间到并发处理》