File size: 3,400 Bytes
29bd9ed
 
9432aa8
29bd9ed
b0132da
fe42adb
b0132da
 
29bd9ed
 
 
 
 
9432aa8
 
 
d7b2837
 
 
 
 
 
b9ab4c6
29bd9ed
 
 
 
 
 
 
 
 
 
1c24e31
 
b9ab4c6
29bd9ed
bdc2de3
 
 
 
29bd9ed
9432aa8
bdc2de3
d7b2837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9432aa8
b7bd888
9432aa8
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
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(model: str = None):
    try:
        # 根据用户提供的SQL语句修改,从 'airs_model_api_keys_view' 视图中获取 'api_key'
        if model:
            response = supabase.from_('airs_model_api_keys_view').select('api_key', 'api_key_id').eq('model_name', model).order('api_key_ran_at', desc=False).limit(1).execute()
        else:
            # 如果没有提供model,则获取所有模型的api_key
            raise HTTPException(status_code=400, detail="请提供模型名称!")
        
        if response.data:
            api_key_info = response.data[0]
            # 在返回api_key_info之前,更新其ran_at字段
            await update_api_key_ran_at(api_key_info.get('api_key_id'))
            return api_key_info
        else:
            logger.error(f"未找到模型 '{model}' 的API密钥信息。")
            raise HTTPException(status_code=404, detail=f"未找到模型 '{model}' 的API密钥信息。", headers={"X-Error-Type": "APIKeyNotFound"})
    except HTTPException as e:
        raise e # 重新抛出已有的HTTPException
    except Exception as e:
        logger.error(f"从Supabase获取API密钥失败: {e}")
        raise HTTPException(status_code=500, detail=f"从Supabase获取API密钥失败: {e}", headers={"X-Error-Type": "SupabaseFetchError"})

async def update_api_key_ran_at(api_key_id: str, 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").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').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)}")