ai-trading-sys/app/api/user/user.py
2025-05-22 19:04:57 +07:00

94 lines
No EOL
3.5 KiB
Python

from fastapi import APIRouter, Query, HTTPException, Body
import json
import os
from typing import Optional
router = APIRouter()
ACCOUNTS_FILE = os.path.join(os.path.dirname(__file__), '../../../accounts.json')
# API lấy danh sách user
@router.get("/users", tags=["User"])
def list_users():
try:
with open(ACCOUNTS_FILE, 'r', encoding='utf-8') as f:
accounts = json.load(f)
return accounts
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error reading accounts file: {e}")
# API thêm user
@router.post("/users", tags=["User"])
def add_user(
id: str = Body(..., description="User ID"),
bybit_api_key: str = Body(..., description="Bybit API Key"),
bybit_api_secret: str = Body(..., description="Bybit API Secret"),
user_name: str = Body(..., description="User name")
):
try:
with open(ACCOUNTS_FILE, 'r+', encoding='utf-8') as f:
accounts = json.load(f)
if any(acc['id'] == id for acc in accounts):
raise HTTPException(status_code=400, detail="ID already exists")
new_user = {
"id": id,
"bybit_api_key": bybit_api_key,
"bybit_api_secret": bybit_api_secret,
"user_name": user_name
}
accounts.append(new_user)
f.seek(0)
json.dump(accounts, f, ensure_ascii=False, indent=2)
f.truncate()
return {"message": "User added successfully"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error writing accounts file: {e}")
# API sửa user
@router.put("/users/{user_id}", tags=["User"])
def update_user(
user_id: str,
bybit_api_key: Optional[str] = Body(None),
bybit_api_secret: Optional[str] = Body(None),
user_name: Optional[str] = Body(None)
):
try:
with open(ACCOUNTS_FILE, 'r+', encoding='utf-8') as f:
accounts = json.load(f)
for acc in accounts:
if acc['id'] == user_id:
if bybit_api_key is not None:
acc['bybit_api_key'] = bybit_api_key
if bybit_api_secret is not None:
acc['bybit_api_secret'] = bybit_api_secret
if user_name is not None:
acc['user_name'] = user_name
f.seek(0)
json.dump(accounts, f, ensure_ascii=False, indent=2)
f.truncate()
return {"message": "User updated successfully"}
raise HTTPException(status_code=404, detail="User ID not found")
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error writing accounts file: {e}")
# API xóa user
@router.delete("/users/{user_id}", tags=["User"])
def delete_user(user_id: str):
try:
with open(ACCOUNTS_FILE, 'r+', encoding='utf-8') as f:
accounts = json.load(f)
new_accounts = [acc for acc in accounts if acc['id'] != user_id]
if len(new_accounts) == len(accounts):
raise HTTPException(status_code=404, detail="User ID not found")
f.seek(0)
json.dump(new_accounts, f, ensure_ascii=False, indent=2)
f.truncate()
return {"message": "User deleted successfully"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error writing accounts file: {e}")