File size: 4,324 Bytes
29bd9ed
 
9432aa8
29bd9ed
b0132da
fe42adb
b0132da
 
29bd9ed
 
 
 
 
9432aa8
 
 
d7b2837
 
 
 
 
 
faaab61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29bd9ed
faaab61
 
29bd9ed
 
 
faaab61
 
 
 
 
1c24e31
faaab61
 
 
29bd9ed
faaab61
 
d7b2837
faaab61
d7b2837
 
 
 
 
 
 
 
 
 
 
 
 
9432aa8
faaab61
9432aa8
b7bd888
 
faaab61
b7bd888
9432aa8
b7bd888
d7b2837
9432aa8
d7b2837
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from supabase import create_client, Client
import os
import logging # 导入logging模块
from fastapi import FastAPI, Request, HTTPException, Depends, status
from dotenv import load_dotenv
from datetime import timezone, timedelta, datetime

load_dotenv()

# Supabase 配置
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")

# 配置日志
logger = logging.getLogger(__name__)

def get_supabase_client() -> Client:
    """Initializes and returns a Supabase client instance."""
    return create_client(SUPABASE_URL, SUPABASE_KEY)

supabase: Client = get_supabase_client()

# async def get_api_key_info(api_type_name: str, lookup_value: str):
#     """
#     根据 API 类型名称和查找值从 Supabase 获取 API 密钥信息。
#     """
#     try:
#         # 直接从 airs_model_api_keys_view_v1 视图中查询
#         response = supabase.from_('airs_model_api_keys_view_v1').select('api_key, api_key_id').eq('api_type', api_type_name).eq('model_name', lookup_value).order('api_key_created_at', desc=False).limit(1).execute()
        
#         if response.data:
#             api_key_info = response.data[0]
#             # 视图返回的 id 是 api_key_id,需要将其映射为 'id' 以保持与之前逻辑的兼容性
#             formatted_api_key_info = {
#                 'api_key': api_key_info.get('api_key'),
#                 'id': api_key_info.get('api_key_id')
#             }
#             # 在返回api_key_info之前,更新其ran_at字段
#             await update_api_key_ran_at(formatted_api_key_info.get('id'))
#             return formatted_api_key_info
#         return None
#     except Exception as e:
#             logger.error(f"Error fetching API key info from view: {e}")
#             return None

async def get_api_key_info(lookup_value: str):
    """
    根据 API 类型名称和查找值从 Supabase 获取 API 密钥信息。
    """
    try:
        # 直接从 airs_model_api_keys_view_v1 视图中查询
        response = supabase.from_('airs_model_api_keys_view_v1').select('api_key, api_key_id').eq('model_name', lookup_value).order('api_key_created_at', desc=False).limit(1).execute()
        
        if response.data:
            api_key_info = response.data[0]
            # 视图返回的 id 是 api_key_id,需要将其映射为 'id' 以保持与之前逻辑的兼容性
            formatted_api_key_info = {
                'api_key': api_key_info.get('api_key'),
                'id': api_key_info.get('api_key_id')
            }
            # 在返回api_key_info之前,更新其ran_at字段
            await update_api_key_ran_at(formatted_api_key_info.get('id'))
            return formatted_api_key_info
        return None
    except Exception as e:
            logger.error(f"Error fetching API key info from view: {e}")
            return None

async def update_api_key_ran_at(api_key_id: int, ran_at_time: datetime = None):
    """
    Updates the 'ran_at' field for a given API key in Supabase.
    If ran_at_time is None, it defaults to the current Beijing time.
    """
    try:
        if ran_at_time is None:
            # 创建北京时间时区对象(UTC+8)
            beijing_tz = timezone(timedelta(hours=8))
            now_beijing = datetime.now(beijing_tz)  # 带时区的datetime对象
            current_local_time = now_beijing.isoformat()
        else:
            current_local_time = ran_at_time.isoformat()

        logger.info(f"尝试更新 API 密钥 {api_key_id} 的 ran_at 为 {current_local_time}")
        response = supabase.table("airs_api_keys_v1").update({"ran_at": current_local_time}).eq("id", api_key_id).execute()
        logger.info(f'API 密钥 {api_key_id} 的 ran_at 更新成功为 {current_local_time}. ')

        # 验证更新是否成功
        verification_response = supabase.from_('airs_api_keys_v1').select('ran_at').eq('id', api_key_id).single().execute()
        verified_ran_at = verification_response.data.get('ran_at')
        logger.info(f"验证:API 密钥 {api_key_id} 的实际 ran_at 值为 {verified_ran_at}")

    except Exception as e:
        logger.error(f"更新API密钥运行时间失败!错误信息:{str(e)}")
        raise HTTPException(status_code=500, detail=f"更新API密钥运行时间失败!错误信息:{str(e)}")