فهرست منبع

优化统计代码

zhuojiaxuan 1 هفته پیش
والد
کامیت
03c3b7c779
2فایلهای تغییر یافته به همراه55 افزوده شده و 52 حذف شده
  1. 52 50
      Controller/AiController.py
  2. 3 2
      Object/RedisObject.py

+ 52 - 50
Controller/AiController.py

@@ -805,16 +805,17 @@ class AiView(View):
     @staticmethod
     def ai_push_count(uid, date_str):
         """ 记录 AI 调用次数(按月累计) """
-        redis_obj = RedisObject(db=7)
-        month_str = date_str[:6]  # "202511"
-        key = f"ai:push:monthly:{month_str}"
-        ttl = 3600 * 24 * 365
         try:
+            redis_obj = RedisObject(db=7)
+            month_str = date_str[:6]  # "202511"
+            key = f"ai:push:monthly:{month_str}"
+            ttl = 3600 * 24 * 90
             redis_obj.hash_field_increment(key, uid, 1, ttl)
         except Exception as e:
             TIME_LOGGER.error(f"AI调用计数失败 uid={uid} error={repr(e)}")
 
-    def ai_push_stats(self, request_dict, response):
+    @staticmethod
+    def ai_push_stats(request_dict, response):
         uid = request_dict.get('uid', None)
         start = request_dict.get('start_time')
         end = request_dict.get('end_time')
@@ -831,49 +832,50 @@ class AiView(View):
         if start_dt > end_dt:
             return response.json(444, '开始月份不能晚于结束月份')
 
-        redis_obj = RedisObject(db=7)
-        total = 0
-        monthly = []
-
-        # 当前月份从开始月份的1号开始
-        cur = start_dt
-        while cur <= end_dt:
-            month_str = cur.strftime("%Y%m")
-            key = f"ai:push:monthly:{month_str}"
-            month_data = {
-                "month": cur.strftime("%Y-%m"),
-                "total_count": 0,  # 当月总次数
-                "users": []  # 当月用户明细(uid和次数)
+        try:
+            redis_obj = RedisObject(db=7)
+            total = 0
+            monthly = []
+
+            # 当前月份从开始月份的1号开始
+            cur = start_dt
+            while cur <= end_dt:
+                month_str = cur.strftime("%Y%m")
+                key = f"ai:push:monthly:{month_str}"
+                month_data = {
+                    "month": cur.strftime("%Y-%m"),
+                    "total_count": 0,  # 当月总次数
+                }
+
+                if uid:
+                    #只返回该设备的数据
+                    count = redis_obj.CONN.hget(key, uid)
+                    count = int(count) if count else 0
+                    month_data["total_count"] = count
+                else:
+                    #返回所有设备的明细和总次数
+                    data = redis_obj.CONN.hgetall(key)
+                    user_list = []
+                    total_month = 0
+                    for user_uid, cnt in data.items():
+                        uid_str = user_uid.decode('utf-8')
+                        count_int = int(cnt.decode('utf-8'))
+                        user_list.append({"uid": uid_str, "count": count_int})
+                        total_month += count_int
+                    month_data["total_count"] = total_month
+                    month_data["users"] = user_list
+
+                total += month_data["total_count"]
+                monthly.append(month_data)
+
+                cur += timedelta(days=32)
+                cur = cur.replace(day=1)
+
+            result = {
+                "uid": uid,
+                "total": total,  # 所有月份的总和
+                "monthly": monthly  # 每个月的明细
             }
-
-            if uid:
-                #只返回该设备的数据
-                count = redis_obj.CONN.hget(key, uid)
-                count = int(count) if count else 0
-                month_data["total_count"] = count
-                month_data["users"].append({"uid": uid, "count": count})
-            else:
-                #返回所有设备的明细和总次数
-                data = redis_obj.CONN.hgetall(key)
-                user_list = []
-                total_month = 0
-                for user_uid, cnt in data.items():
-                    uid_str = user_uid.decode('utf-8')
-                    count_int = int(cnt.decode('utf-8'))
-                    user_list.append({"uid": uid_str, "count": count_int})
-                    total_month += count_int
-                month_data["total_count"] = total_month
-                month_data["users"] = user_list
-
-            total += month_data["total_count"]
-            monthly.append(month_data)
-
-            cur += timedelta(days=32)
-            cur = cur.replace(day=1)
-
-        result = {
-            "uid": uid,
-            "total": total,  # 所有月份的总和
-            "monthly": monthly  # 每个月的明细
-        }
-        return response.json(0, result)
+            return response.json(0, result)
+        except Exception as e:
+            return response.json(500, f"error_line:{e.__traceback__.tb_lineno}, error_msg:{repr(e)}")

+ 3 - 2
Object/RedisObject.py

@@ -1,6 +1,7 @@
+import logging
 import redis
 from AnsjerPush.config import REDIS_ADDRESS, CONFIG_INFO, CONFIG_US
-
+TIME_LOGGER = logging.getLogger('time')
 # 本地调试把注释打开
 # REDIS_ADDRESS = '127.0.0.1'
 
@@ -150,5 +151,5 @@ class RedisObject:
             return True
         except Exception as e:
             # 发生异常时打印错误信息,便于调试
-            print(f"增值或设置过期时间时发生错误: {repr(e)}")
+            TIME_LOGGER.error(f"增值或设置过期时间时发生错误: {repr(e)}")
             return False