Spaces:
Sleeping
Sleeping
| 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)}") | |