You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
import os
|
|
from typing import Union, Dict, List
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
import json
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
# 读取 JSON 文件
|
|
class DataLoader:
|
|
_data = None # 类变量,用于存储加载的 JSON 数据
|
|
|
|
@staticmethod
|
|
def load_json_data(file_path):
|
|
print(f"current fileop.py path: {file_path}")
|
|
if DataLoader._data is None:
|
|
try:
|
|
with open(file_path, "r") as file:
|
|
DataLoader._data = json.load(file)
|
|
except FileNotFoundError:
|
|
raise HTTPException(status_code=500, detail="File not found")
|
|
except json.JSONDecodeError:
|
|
raise HTTPException(status_code=500, detail="Invalid JSON")
|
|
return DataLoader._data
|
|
|
|
|
|
# 定义一个路由来返回 JSON 数据
|
|
@router.get("/get_data")
|
|
async def get_data(
|
|
) :
|
|
current_file = os.path.abspath(__file__)
|
|
current_dir = os.path.dirname(current_file)
|
|
project_root = os.path.dirname(current_dir)
|
|
assets_dir = os.path.join(project_root, "assets")
|
|
config_path = os.path.join(assets_dir, "config.json")
|
|
data = DataLoader.load_json_data(config_path)
|
|
return data
|