liurenchaxin/scripts/api_health_check.py

77 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
API健康检查模块
用于测试与外部服务的连接如OpenRouter和RapidAPI。
"""
import os
import requests
import sys
from pathlib import Path
# 将项目根目录添加到Python路径以便导入config模块
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from config.settings import get_openrouter_key, get_rapidapi_key
def test_openrouter_api() -> bool:
"""
测试与OpenRouter API的连接和认证。
"""
api_key = get_openrouter_key()
if not api_key:
print("❌ OpenRouter API Key not found.")
return False
url = "https://openrouter.ai/api/v1/models"
headers = {"Authorization": f"Bearer {api_key}"}
try:
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
print("✅ OpenRouter API connection successful.")
return True
else:
print(f"❌ OpenRouter API connection failed. Status: {response.status_code}, Response: {response.text[:100]}")
return False
except requests.RequestException as e:
print(f"❌ OpenRouter API request failed: {e}")
return False
def test_rapidapi_connection() -> bool:
"""
测试与RapidAPI的连接和认证。
这里我们使用一个简单的、免费的API端点进行测试。
"""
api_key = get_rapidapi_key()
if not api_key:
print("❌ RapidAPI Key not found.")
return False
# 使用一个通用的、通常可用的RapidAPI端点进行测试
url = "https://alpha-vantage.p.rapidapi.com/query"
querystring = {"function":"TOP_GAINERS_LOSERS"}
headers = {
"x-rapidapi-host": "alpha-vantage.p.rapidapi.com",
"x-rapidapi-key": api_key
}
try:
response = requests.get(url, headers=headers, params=querystring, timeout=15)
# Alpha Vantage的免费套餐可能会返回错误但只要RapidAPI认证通过状态码就不是401或403
if response.status_code not in [401, 403]:
print(f"✅ RapidAPI connection successful (Status: {response.status_code}).")
return True
else:
print(f"❌ RapidAPI authentication failed. Status: {response.status_code}, Response: {response.text[:100]}")
return False
except requests.RequestException as e:
print(f"❌ RapidAPI request failed: {e}")
return False
if __name__ == "__main__":
print("🩺 Running API Health Checks...")
test_openrouter_api()
test_rapidapi_connection()