100 lines
3.0 KiB
Python
100 lines
3.0 KiB
Python
"""
|
|
配置管理API
|
|
"""
|
|
from fastapi import APIRouter, HTTPException
|
|
from api.models.config import ConfigItem, ConfigUpdate
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# 添加项目根目录到路径
|
|
project_root = Path(__file__).parent.parent.parent.parent
|
|
sys.path.insert(0, str(project_root))
|
|
sys.path.insert(0, str(project_root / 'backend'))
|
|
|
|
from database.models import TradingConfig
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/")
|
|
async def get_all_configs():
|
|
"""获取所有配置"""
|
|
try:
|
|
configs = TradingConfig.get_all()
|
|
result = {}
|
|
for config in configs:
|
|
result[config['config_key']] = {
|
|
'value': TradingConfig._convert_value(
|
|
config['config_value'],
|
|
config['config_type']
|
|
),
|
|
'type': config['config_type'],
|
|
'category': config['category'],
|
|
'description': config['description']
|
|
}
|
|
return result
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.get("/{key}")
|
|
async def get_config(key: str):
|
|
"""获取单个配置"""
|
|
try:
|
|
config = TradingConfig.get(key)
|
|
if not config:
|
|
raise HTTPException(status_code=404, detail="Config not found")
|
|
|
|
return {
|
|
'key': config['config_key'],
|
|
'value': TradingConfig._convert_value(
|
|
config['config_value'],
|
|
config['config_type']
|
|
),
|
|
'type': config['config_type'],
|
|
'category': config['category'],
|
|
'description': config['description']
|
|
}
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.put("/{key}")
|
|
async def update_config(key: str, item: ConfigUpdate):
|
|
"""更新配置"""
|
|
try:
|
|
# 获取现有配置以确定类型和分类
|
|
existing = TradingConfig.get(key)
|
|
if not existing:
|
|
raise HTTPException(status_code=404, detail="Config not found")
|
|
|
|
config_type = item.type or existing['config_type']
|
|
category = item.category or existing['category']
|
|
description = item.description or existing['description']
|
|
|
|
TradingConfig.set(key, item.value, config_type, category, description)
|
|
return {"message": "Config updated", "key": key}
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.post("/batch")
|
|
async def update_configs_batch(configs: list[ConfigItem]):
|
|
"""批量更新配置"""
|
|
try:
|
|
for item in configs:
|
|
TradingConfig.set(
|
|
item.key,
|
|
item.value,
|
|
item.type,
|
|
item.category,
|
|
item.description
|
|
)
|
|
return {"message": f"{len(configs)} configs updated"}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|