File size: 1,769 Bytes
954be92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
配置管理模块
从环境变量加载配置,支持多 API Key
"""
import os
from typing import List
from functools import lru_cache
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()


class Settings:
    """应用配置类"""
    
    def __init__(self):
        # API Keys 列表(支持多个,逗号分隔)
        api_keys_str = os.getenv("API_KEYS", "")
        self.API_KEYS: List[str] = [k.strip() for k in api_keys_str.split(",") if k.strip()]
        
        # 基准货币
        self.BASE_CURRENCY: str = os.getenv("BASE_CURRENCY", "CNY")
        
        # 缓存更新间隔(秒)
        self.CACHE_UPDATE_INTERVAL: int = int(os.getenv("CACHE_UPDATE_INTERVAL", "3600"))
        
        # API 请求超时时间(秒)
        self.REQUEST_TIMEOUT: int = int(os.getenv("REQUEST_TIMEOUT", "10"))
        
        # 最大重试次数
        self.MAX_RETRIES: int = int(os.getenv("MAX_RETRIES", "3"))
        
        # 服务端口
        self.SERVER_PORT: int = int(os.getenv("SERVER_PORT", "8000"))
        
        # 常用货币列表(前端优先展示)
        self.PRIORITY_CURRENCIES: List[str] = [
            "CNY", "USD", "EUR", "GBP", "JPY", "HKD", "AUD", "CAD", 
            "CHF", "SGD", "KRW", "TWD", "THB", "MYR", "INR", "RUB"
        ]
        
        # API 基础 URL
        self.API_BASE_URL: str = "https://v6.exchangerate-api.com/v6"
    
    def validate(self) -> bool:
        """验证配置是否有效"""
        if not self.API_KEYS:
            raise ValueError("API_KEYS 不能为空,请在 .env 文件中配置")
        return True


@lru_cache()
def get_settings() -> Settings:
    """获取配置单例"""
    settings = Settings()
    settings.validate()
    return settings