FISHYA commited on
Commit
bd78192
·
verified ·
1 Parent(s): b8e3b0c

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +28 -2
app/main.py CHANGED
@@ -51,16 +51,31 @@ STATS_FILE = "stats.json"
51
 
52
  def load_stats():
53
  try:
54
- with open(STATS_FILE, "r") as f:
 
 
 
55
  return json.load(f)
56
  except (FileNotFoundError, json.JSONDecodeError):
57
- return {
 
58
  "total_calls": 0,
59
  "today_calls": 0,
60
  "total_tokens": 0,
61
  "today_tokens": 0,
62
  "last_reset": datetime.now().isoformat()
63
  }
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  def save_stats(stats):
66
  with open(STATS_FILE, "w") as f:
@@ -367,6 +382,17 @@ async def global_exception_handler(request: Request, exc: Exception):
367
  return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=ErrorResponse(message=str(exc), type="internal_error").dict())
368
 
369
 
 
 
 
 
 
 
 
 
 
 
 
370
  @app.get("/", response_class=HTMLResponse)
371
  async def root():
372
  html_content = f"""
 
51
 
52
  def load_stats():
53
  try:
54
+ # 使用绝对路径确保文件位置正确
55
+ stats_path = os.path.abspath(STATS_FILE)
56
+ # 先尝试读取现有文件
57
+ with open(stats_path, "r") as f:
58
  return json.load(f)
59
  except (FileNotFoundError, json.JSONDecodeError):
60
+ # 初始化并保存新文件
61
+ initial_stats = {
62
  "total_calls": 0,
63
  "today_calls": 0,
64
  "total_tokens": 0,
65
  "today_tokens": 0,
66
  "last_reset": datetime.now().isoformat()
67
  }
68
+ try:
69
+ # 确保目录存在
70
+ os.makedirs(os.path.dirname(stats_path), exist_ok=True)
71
+ # 写入初始数据
72
+ with open(stats_path, "w") as f:
73
+ json.dump(initial_stats, f, indent=2)
74
+ logger.info(f"已创建初始统计文件: {stats_path}")
75
+ return initial_stats
76
+ except Exception as e:
77
+ logger.error(f"创建统计文件失败: {str(e)}")
78
+ return initial_stats
79
 
80
  def save_stats(stats):
81
  with open(STATS_FILE, "w") as f:
 
382
  return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=ErrorResponse(message=str(exc), type="internal_error").dict())
383
 
384
 
385
+ @app.get("/api/stats")
386
+ async def get_stats():
387
+ stats = load_stats()
388
+ return {
389
+ "today_calls": stats["today_calls"],
390
+ "total_calls": stats["total_calls"],
391
+ "today_tokens": stats["today_tokens"],
392
+ "total_tokens": stats["total_tokens"],
393
+ "last_reset": stats["last_reset"]
394
+ }
395
+
396
  @app.get("/", response_class=HTMLResponse)
397
  async def root():
398
  html_content = f"""