| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- """
- Application configuration module.
- Manages JWT and OAuth settings from YAML configuration file.
- Supports dev/prod environments via APP_ENV environment variable.
- """
- import os
- import secrets
- import logging
- import yaml
- from pathlib import Path
- from typing import Dict, Any
- logger = logging.getLogger(__name__)
- def get_config_path() -> Path:
- """
- 根据 APP_ENV 环境变量获取配置文件路径
- APP_ENV=prod -> config.prod.yaml
- APP_ENV=dev -> config.dev.yaml
- 默认 -> config.yaml (兼容旧配置)
- """
- app_env = os.getenv("APP_ENV", "").lower()
- base_path = Path(__file__).parent
-
- if app_env == "prod":
- config_file = base_path / "config.prod.yaml"
- logger.info("使用生产环境配置: config.prod.yaml")
- elif app_env == "dev":
- config_file = base_path / "config.dev.yaml"
- logger.info("使用开发环境配置: config.dev.yaml")
- else:
- # 兼容旧的 config.yaml
- print("默认使用开发环境")
- config_file = base_path / "config.dev.yaml"
- if app_env:
- logger.warning(f"未知的 APP_ENV 值: {app_env},使用默认 config.yaml")
-
- return config_file
- class Settings:
- """Application settings loaded from config.yaml."""
-
- def __init__(self):
- """Load configuration from YAML file."""
- config_path = get_config_path()
-
- if not config_path.exists():
- raise FileNotFoundError(f"配置文件不存在: {config_path}")
-
- with open(config_path, 'r', encoding='utf-8') as f:
- config = yaml.safe_load(f)
-
- # 记录当前环境(统一转小写)
- self.APP_ENV = os.getenv("APP_ENV", "default").lower()
- print(f"[Config] APP_ENV={self.APP_ENV}, 配置文件={config_path}")
-
- # JWT Settings
- jwt_config = config.get('jwt', {})
- self.JWT_SECRET_KEY = jwt_config.get('secret_key', secrets.token_urlsafe(32))
- self.JWT_ALGORITHM = jwt_config.get('algorithm', 'HS256')
- self.ACCESS_TOKEN_EXPIRE_MINUTES = jwt_config.get('access_token_expire_minutes', 15)
- self.REFRESH_TOKEN_EXPIRE_DAYS = jwt_config.get('refresh_token_expire_days', 7)
-
- # Database Settings (MySQL only)
- db_config = config.get('database', {})
-
- # MySQL Settings
- mysql_config = db_config.get('mysql', {})
- self.MYSQL_HOST = mysql_config.get('host', 'localhost')
- self.MYSQL_PORT = mysql_config.get('port', 3306)
- self.MYSQL_USER = mysql_config.get('user', 'root')
- self.MYSQL_PASSWORD = mysql_config.get('password', '')
- self.MYSQL_DATABASE = mysql_config.get('database', 'annotation_platform')
-
- # OAuth Settings
- oauth_config = config.get('oauth', {})
- self.OAUTH_ENABLED = oauth_config.get('enabled', False)
- self.OAUTH_BASE_URL = oauth_config.get('base_url', '')
- self.OAUTH_CLIENT_ID = oauth_config.get('client_id', '')
- self.OAUTH_CLIENT_SECRET = oauth_config.get('client_secret', '')
- self.OAUTH_REDIRECT_URI = oauth_config.get('redirect_uri', '')
- self.OAUTH_SCOPE = oauth_config.get('scope', 'profile email')
-
- # OAuth Endpoints
- self.OAUTH_AUTHORIZE_ENDPOINT = oauth_config.get('authorize_endpoint', '/oauth/authorize')
- self.OAUTH_TOKEN_ENDPOINT = oauth_config.get('token_endpoint', '/oauth/token')
- self.OAUTH_USERINFO_ENDPOINT = oauth_config.get('userinfo_endpoint', '/oauth/userinfo')
- self.OAUTH_REVOKE_ENDPOINT = oauth_config.get('revoke_endpoint', '/oauth/revoke')
-
- # Server Settings
- server_config = config.get('server', {})
- self.SERVER_HOST = server_config.get('host', '0.0.0.0')
- self.SERVER_PORT = server_config.get('port', 8000)
- self.SERVER_RELOAD = server_config.get('reload', True)
-
- # Warn if using default JWT secret in production
- if self.APP_ENV == "prod" and self.JWT_SECRET_KEY in ['your-secret-key-here', 'CHANGE_THIS_TO_A_SECURE_RANDOM_KEY']:
- logger.warning("生产环境使用默认 JWT_SECRET_KEY,请立即修改 config.prod.yaml!")
- elif self.JWT_SECRET_KEY == 'your-secret-key-here':
- logger.warning(f"使用默认 JWT_SECRET_KEY,生产环境请修改配置文件!(当前环境: {self.APP_ENV})")
- # Create settings instance
- settings = Settings()
|