测试代码改为以test_开头

This commit is contained in:
mark.tian
2025-12-09 15:41:10 +08:00
parent e903a80261
commit d10c403ddc
9 changed files with 557 additions and 95 deletions

View File

@@ -8,113 +8,123 @@ from api_config import API_CONFIG, RETRY_CONFIG
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@app.task(bind=True, max_retries=None) @app.task(bind=True, max_retries=None)
def invoke_call_api_task(self, api_key='main_api', custom_payload=None): def invoke_call_api_task(self):
"""调用呼叫任务API """遍历API配置文件中的所有API配置并调用接口"""
Args:
api_key: 呼叫任务API配置的键名(如 'call_api', 'voice_api')
custom_payload: 自定义呼叫参数,如果为None则使用默认参数
"""
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
logger.info(f"呼叫任务API开始执行 - 当前时间: {current_time}") logger.info(f"开始遍历API配置文件执行呼叫任务 - 当前时间: {current_time}")
# 获取重试配置 # 获取重试配置
max_retries = RETRY_CONFIG['max_retries'] max_retries = RETRY_CONFIG['max_retries']
retry_delay = RETRY_CONFIG['retry_delay'] retry_delay = RETRY_CONFIG['retry_delay']
retry_on_status = RETRY_CONFIG['retry_on_status'] retry_on_status = RETRY_CONFIG['retry_on_status']
# 获取呼叫任务API配置 # 遍历所有API配置
call_config = API_CONFIG[api_key] results = []
call_url = call_config['url'] success_count = 0
method = call_config['method'].upper()
headers = call_config['headers']
timeout = call_config['timeout']
# 构建呼叫参数 for api_key, call_config in API_CONFIG.items():
if custom_payload is None: logger.info(f"开始处理API配置: {api_key}")
# 直接使用配置文件中的body作为呼叫参数
call_url = call_config['url']
method = call_config['method'].upper()
headers = call_config['headers']
timeout = call_config['timeout']
payload = call_config['body'] payload = call_config['body']
else:
payload = custom_payload
try: try:
logger.info(f"正在调用呼叫任务API: {method} {call_url}") logger.info(f"正在调用呼叫任务API: {method} {call_url}")
# 根据method选择请求方式 # 根据method选择请求方式
if method == 'POST': if method == 'POST':
response = requests.post(call_url, headers=headers, json=payload, timeout=timeout) response = requests.post(call_url, headers=headers, json=payload, timeout=timeout)
elif method == 'GET': elif method == 'GET':
response = requests.get(call_url, headers=headers, params=payload, timeout=timeout) response = requests.get(call_url, headers=headers, params=payload, timeout=timeout)
elif method == 'PUT': elif method == 'PUT':
response = requests.put(call_url, headers=headers, json=payload, timeout=timeout) response = requests.put(call_url, headers=headers, json=payload, timeout=timeout)
elif method == 'DELETE': elif method == 'DELETE':
response = requests.delete(call_url, headers=headers, timeout=timeout) response = requests.delete(call_url, headers=headers, timeout=timeout)
else:
raise ValueError(f"不支持的HTTP方法: {method}")
# 检查响应状态
if response.status_code in [200, 201, 204]: # 成功状态码
try:
result_data = response.json()
except:
result_data = {'response': response.text}
logger.info(f"呼叫任务API调用成功,响应数据: {result_data}")
print(f"[{current_time}] ✅ 呼叫任务API成功 - {method} {call_url}")
return {
'status': 'success',
'message': f'呼叫任务API调用成功 ({method})',
'response': result_data,
'timestamp': current_time,
'retry_count': getattr(self.request, 'retries', 0),
'call_api_key': api_key
}
elif response.status_code in retry_on_status:
# 需要重试的状态码
current_retry = getattr(self.request, 'retries', 0)
if current_retry < max_retries:
logger.warning(f"呼叫任务API需要重试,当前重试次数: {current_retry + 1}/{max_retries}")
print(f"[{current_time}] 🔄 呼叫任务API失败,正在重试 ({current_retry + 1}/{max_retries}) - 状态码: {response.status_code}")
raise self.retry(countdown=retry_delay, exc=Exception(f"呼叫任务API失败,状态码: {response.status_code}"))
else: else:
logger.error(f"呼叫任务API失败,已达到最大重试次数: {max_retries}") raise ValueError(f"不支持的HTTP方法: {method}")
print(f"[{current_time}] ❌ 呼叫任务API失败,已达到最大重试次数 - 状态码: {response.status_code}")
return { # 检查响应状态
if response.status_code in [200, 201, 204]: # 成功状态码
try:
result_data = response.json()
except:
result_data = {'response': response.text}
logger.info(f"呼叫任务API调用成功,响应数据: {result_data}")
print(f"[{current_time}] ✅ 呼叫任务API成功 ({api_key}) - {method} {call_url}")
success_count += 1
results.append({
'call_api_key': api_key,
'status': 'success',
'message': f'呼叫任务API调用成功 ({method})',
'response': result_data,
'timestamp': current_time,
'retry_count': getattr(self.request, 'retries', 0)
})
elif response.status_code in retry_on_status:
# 需要重试的状态码
current_retry = getattr(self.request, 'retries', 0)
if current_retry < max_retries:
logger.warning(f"呼叫任务API需要重试,当前重试次数: {current_retry + 1}/{max_retries}")
print(f"[{current_time}] 🔄 呼叫任务API失败,正在重试 ({current_retry + 1}/{max_retries}) - {api_key} - 状态码: {response.status_code}")
raise self.retry(countdown=retry_delay, exc=Exception(f"呼叫任务API失败,状态码: {response.status_code}"))
else:
logger.error(f"呼叫任务API失败,已达到最大重试次数: {max_retries}")
print(f"[{current_time}] ❌ 呼叫任务API失败,已达到最大重试次数 - {api_key} - 状态码: {response.status_code}")
results.append({
'call_api_key': api_key,
'status': 'failed',
'message': f'呼叫任务API失败,已达到最大重试次数: {max_retries}',
'response': response.text,
'timestamp': current_time,
'retry_count': current_retry + 1
})
else:
# 其他失败状态码,不重试
logger.error(f"呼叫任务API失败,状态码: {response.status_code}, 响应: {response.text}")
print(f"[{current_time}] ❌ 呼叫任务API失败 - {api_key} - 状态码: {response.status_code}")
results.append({
'call_api_key': api_key,
'status': 'failed', 'status': 'failed',
'message': f'呼叫任务API失败,已达到最大重试次数: {max_retries}', 'message': f'呼叫任务API失败,状态码: {response.status_code}',
'response': response.text, 'response': response.text,
'timestamp': current_time, 'timestamp': current_time,
'retry_count': current_retry + 1, 'retry_count': getattr(self.request, 'retries', 0)
'call_api_key': api_key })
}
else:
# 其他失败状态码,不重试
logger.error(f"呼叫任务API失败,状态码: {response.status_code}, 响应: {response.text}")
print(f"[{current_time}] ❌ 呼叫任务API失败 - 状态码: {response.status_code}")
return {
'status': 'failed',
'message': f'呼叫任务API失败,状态码: {response.status_code}',
'response': response.text,
'timestamp': current_time,
'retry_count': getattr(self.request, 'retries', 0),
'call_api_key': api_key
}
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
# 网络异常,需要重试 # 网络异常,需要重试
current_retry = getattr(self.request, 'retries', 0) current_retry = getattr(self.request, 'retries', 0)
if current_retry < max_retries: if current_retry < max_retries:
logger.warning(f"呼叫任务API异常,需要重试,当前重试次数: {current_retry + 1}/{max_retries}") logger.warning(f"呼叫任务API异常,需要重试,当前重试次数: {current_retry + 1}/{max_retries}")
print(f"[{current_time}] 🔄 呼叫任务API异常,正在重试 ({current_retry + 1}/{max_retries}) - 异常: {str(e)}") print(f"[{current_time}] 🔄 呼叫任务API异常,正在重试 ({current_retry + 1}/{max_retries}) - {api_key} - 异常: {str(e)}")
raise self.retry(countdown=retry_delay, exc=e) raise self.retry(countdown=retry_delay, exc=e)
else: else:
logger.error(f"呼叫任务API异常,已达到最大重试次数: {max_retries}") logger.error(f"呼叫任务API异常,已达到最大重试次数: {max_retries}")
print(f"[{current_time}] ❌ 呼叫任务API异常,已达到最大重试次数 - 异常: {str(e)}") print(f"[{current_time}] ❌ 呼叫任务API异常,已达到最大重试次数 - {api_key} - 异常: {str(e)}")
return { results.append({
'status': 'error', 'call_api_key': api_key,
'message': f'呼叫任务API异常,已达到最大重试次数: {max_retries}', 'status': 'error',
'error': str(e), 'message': f'呼叫任务API异常,已达到最大重试次数: {max_retries}',
'timestamp': current_time, 'error': str(e),
'retry_count': current_retry + 1, 'timestamp': current_time,
'call_api_key': api_key 'retry_count': current_retry + 1
} })
# 汇总结果
total_count = len(results)
logger.info(f"遍历API配置文件执行完成 - 成功: {success_count}/{total_count}")
print(f"[{current_time}] 📊 任务汇总 - 成功: {success_count}/{total_count}")
return {
'status': 'completed',
'total_apis': total_count,
'success_count': success_count,
'failed_count': total_count - success_count,
'results': results,
'timestamp': current_time
}

View File

@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""测试遍历API配置列表执行调用任务"""
from invoke_call_api_task import invoke_call_api_task
from api_config import API_CONFIG
import time
def main():
"""遍历API配置文件中的所有API并执行调用"""
print("🚀 开始遍历API配置列表执行调用任务")
print("=" * 60)
results = []
for api_key, config in API_CONFIG.items():
print(f"\n📞 正在调用API: {api_key}")
print(f" URL: {config['url']}")
print(f" 方法: {config['method']}")
print(f" 超时: {config['timeout']}秒")
# 执行API调用任务
try:
result = invoke_call_api_task.delay(api_key=api_key)
# 等待任务完成并获取结果
task_result = result.get(timeout=config['timeout'] + 10)
print(f" 结果: {task_result['status']}")
print(f" 消息: {task_result['message']}")
if task_result['status'] == 'success':
print(f" ✅ 成功")
else:
print(f" ❌ 失败")
results.append({
'api_key': api_key,
'status': task_result['status'],
'result': task_result
})
except Exception as e:
print(f" ❌ 异常: {str(e)}")
results.append({
'api_key': api_key,
'status': 'error',
'error': str(e)
})
# 短暂延迟避免请求过于频繁
time.sleep(1)
# 汇总结果
print("\n" + "=" * 60)
print("📊 任务执行汇总:")
success_count = len([r for r in results if r['status'] == 'success'])
total_count = len(results)
for result in results:
status_icon = "✅" if result['status'] == 'success' else "❌"
print(f" {status_icon} {result['api_key']}: {result['status']}")
print(f"\n总计: {success_count}/{total_count} 成功")
print("🎯 任务执行完成")
if __name__ == "__main__":
main()

73
test_celery_api_list.py Normal file
View File

@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""使用Celery任务遍历API配置列表执行调用"""
from invoke_call_api_task import invoke_call_api_task
from api_config import API_CONFIG
def test_celery_api_list():
"""使用Celery异步任务遍历所有API配置"""
print("🚀 使用Celery任务遍历API配置列表")
print("=" * 50)
results = []
task_ids = []
# 提交所有任务
for api_key in API_CONFIG.keys():
print(f"📤 提交任务: {api_key}")
# 提交异步任务
task_result = invoke_call_api_task.delay(api_key=api_key)
task_ids.append((api_key, task_result))
results.append({
'api_key': api_key,
'task_id': task_result.id,
'status': 'submitted'
})
print(f"\n⏳ 等待 {len(task_ids)} 个任务完成...")
# 等待所有任务完成
for api_key, task_result in task_ids:
try:
# 等待任务结果
result = task_result.get(timeout=60)
# 更新结果
for r in results:
if r['api_key'] == api_key:
r['status'] = result['status']
r['message'] = result['message']
r['task_result'] = result
break
status_icon = "✅" if result['status'] == 'success' else "❌"
print(f" {status_icon} {api_key}: {result['status']}")
except Exception as e:
for r in results:
if r['api_key'] == api_key:
r['status'] = 'error'
r['message'] = str(e)
break
print(f" ❌ {api_key}: 错误 - {str(e)[:30]}")
# 汇总
print("\n" + "=" * 50)
print("📊 Celery任务执行汇总:")
success_count = len([r for r in results if r['status'] == 'success'])
total_count = len(results)
for result in results:
status_icon = "✅" if result['status'] == 'success' else "❌"
print(f" {status_icon} {result['api_key']}: {result['status']}")
print(f"\n🎯 总计: {success_count}/{total_count} 成功")
print("✨ 所有任务执行完成")
return results
if __name__ == "__main__":
test_celery_api_list()

129
test_direct_api.py Normal file
View File

@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""直接测试API调用(不使用Celery)"""
import requests
from datetime import datetime
from api_config import API_CONFIG, RETRY_CONFIG
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def call_api_direct(api_key='main_api', custom_payload=None):
"""直接调用API(复制invoke_call_api_task的核心逻辑)"""
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
logger.info(f"呼叫任务API开始执行 - 当前时间: {current_time}")
# 获取重试配置
max_retries = RETRY_CONFIG['max_retries']
retry_delay = RETRY_CONFIG['retry_delay']
retry_on_status = RETRY_CONFIG['retry_on_status']
# 获取呼叫任务API配置
call_config = API_CONFIG[api_key]
call_url = call_config['url']
method = call_config['method'].upper()
headers = call_config['headers']
timeout = call_config['timeout']
# 构建呼叫参数
if custom_payload is None:
payload = call_config['body']
else:
payload = custom_payload
try:
logger.info(f"正在调用呼叫任务API: {method} {call_url}")
# 根据method选择请求方式
if method == 'POST':
response = requests.post(call_url, headers=headers, json=payload, timeout=timeout)
elif method == 'GET':
response = requests.get(call_url, headers=headers, params=payload, timeout=timeout)
elif method == 'PUT':
response = requests.put(call_url, headers=headers, json=payload, timeout=timeout)
elif method == 'DELETE':
response = requests.delete(call_url, headers=headers, timeout=timeout)
else:
raise ValueError(f"不支持的HTTP方法: {method}")
# 检查响应状态
if response.status_code in [200, 201, 204]:
try:
result_data = response.json()
except:
result_data = {'response': response.text}
logger.info(f"呼叫任务API调用成功,响应数据: {result_data}")
print(f"[{current_time}] ✅ 呼叫任务API成功 - {method} {call_url}")
return {
'status': 'success',
'message': f'呼叫任务API调用成功 ({method})',
'response': result_data,
'timestamp': current_time,
'api_key': api_key
}
else:
logger.error(f"呼叫任务API失败,状态码: {response.status_code}, 响应: {response.text}")
print(f"[{current_time}] ❌ 呼叫任务API失败 - 状态码: {response.status_code}")
return {
'status': 'failed',
'message': f'呼叫任务API失败,状态码: {response.status_code}',
'response': response.text,
'timestamp': current_time,
'api_key': api_key
}
except requests.exceptions.RequestException as e:
logger.error(f"呼叫任务API异常: {str(e)}")
print(f"[{current_time}] ❌ 呼叫任务API异常 - {str(e)}")
return {
'status': 'error',
'message': f'呼叫任务API异常: {str(e)}',
'timestamp': current_time,
'api_key': api_key
}
def main():
"""遍历所有API配置并执行调用"""
print("🚀 开始遍历API配置列表执行直接调用")
print("=" * 60)
results = []
for api_key, config in API_CONFIG.items():
print(f"\n📞 正在调用API: {api_key}")
print(f" URL: {config['url']}")
print(f" 方法: {config['method']}")
print(f" 超时: {config['timeout']}秒")
# 直接调用API函数
result = call_api_direct(api_key=api_key)
status_icon = "✅" if result['status'] == 'success' else "❌"
print(f" 结果: {status_icon} {result['status']}")
print(f" 消息: {result['message']}")
results.append({
'api_key': api_key,
'status': result['status'],
'message': result['message'],
'result': result
})
# 汇总结果
print("\n" + "=" * 60)
print("📊 任务执行汇总:")
success_count = len([r for r in results if r['status'] == 'success'])
total_count = len(results)
for result in results:
status_icon = "✅" if result['status'] == 'success' else "❌"
print(f" {status_icon} {result['api_key']}: {result['status']}")
print(f"\n🎯 总计: {success_count}/{total_count} 成功")
print("✨ 任务执行完成")
if __name__ == "__main__":
main()

45
test_quick_api.py Normal file
View File

@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""快速测试API列表调用"""
import requests
from api_config import API_CONFIG
from datetime import datetime
def quick_test():
print("🚀 快速测试API列表调用")
print("=" * 40)
success = 0
total = 0
for api_key, config in API_CONFIG.items():
total += 1
print(f"\n📞 {api_key} ({config['method']})")
try:
if config['method'] == 'GET':
resp = requests.get(config['url'], headers=config['headers'],
params=config['body'], timeout=config['timeout'])
elif config['method'] == 'POST':
resp = requests.post(config['url'], headers=config['headers'],
json=config['body'], timeout=config['timeout'])
elif config['method'] == 'PUT':
resp = requests.put(config['url'], headers=config['headers'],
json=config['body'], timeout=config['timeout'])
else:
resp = requests.delete(config['url'], headers=config['headers'],
timeout=config['timeout'])
if resp.status_code in [200, 201, 204]:
print(f" ✅ 成功 - 状态码: {resp.status_code}")
success += 1
else:
print(f" ❌ 失败 - 状态码: {resp.status_code}")
except Exception as e:
print(f" ❌ 异常: {str(e)[:50]}")
print(f"\n📊 结果: {success}/{total} 成功")
if __name__ == "__main__":
quick_test()

32
test_quick_updated.py Normal file
View File

@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""快速测试更新后的invoke_call_api_task方法"""
import logging
logging.basicConfig(level=logging.INFO)
from invoke_call_api_task import invoke_call_api_task
from api_config import API_CONFIG
def quick_test():
print("🚀 快速测试更新后的invoke_call_api_task")
print("=" * 40)
# 创建任务实例
task_instance = invoke_call_api_task()
# 执行任务
result = task_instance.run()
print(f"\n📊 执行汇总:")
print(f" 状态: {result['status']}")
print(f" 总数: {result['total_apis']}")
print(f" 成功: {result['success_count']}")
print(f" 失败: {result['failed_count']}")
print(f"\n📋 API调用结果:")
for api_result in result['results']:
icon = "✅" if api_result['status'] == 'success' else "❌"
print(f" {icon} {api_result['call_api_key']} - {api_result['status']}")
if __name__ == "__main__":
quick_test()

67
test_simple_api_list.py Normal file
View File

@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""简单测试:遍历API配置列表执行调用(同步方式)"""
from invoke_call_api_task import invoke_call_api_task
from api_config import API_CONFIG
import time
def main():
"""直接调用函数遍历所有API配置"""
print("🚀 开始遍历API配置列表执行调用")
print("=" * 50)
results = []
for api_key, config in API_CONFIG.items():
print(f"\n📞 正在调用API: {api_key}")
print(f" URL: {config['url']}")
print(f" 方法: {config['method']}")
try:
# 使用异步方式执行Celery任务
from celery import current_app
# 提交异步任务
async_result = invoke_call_api_task.delay(api_key=api_key)
# 等待任务完成
result = async_result.get(timeout=60)
print(f" 状态: {result['status']}")
print(f" 消息: {result['message']}")
status_icon = "✅" if result['status'] == 'success' else "❌"
print(f" 结果: {status_icon} {result['status']}")
results.append({
'api_key': api_key,
'status': result['status'],
'message': result['message']
})
except Exception as e:
print(f" ❌ 异常: {str(e)}")
results.append({
'api_key': api_key,
'status': 'error',
'message': str(e)
})
# 短暂延迟
time.sleep(1)
# 汇总
print("\n" + "=" * 50)
print("📊 执行汇总:")
success_count = len([r for r in results if r['status'] == 'success'])
total_count = len(results)
for result in results:
status_icon = "✅" if result['status'] == 'success' else "❌"
print(f" {status_icon} {result['api_key']}: {result['message']}")
print(f"\n🎯 总计: {success_count}/{total_count} 成功")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""测试修改后的invoke_call_api_task方法"""
import logging
logging.basicConfig(level=logging.INFO)
from invoke_call_api_task import invoke_call_api_task
def test_updated_method():
"""测试更新后的invoke_call_api_task方法"""
print("🚀 测试修改后的invoke_call_api_task方法")
print("=" * 50)
try:
# 直接调用任务实例来测试逻辑
task_instance = invoke_call_api_task()
result = task_instance.run()
print(f"\n📊 执行结果:")
print(f" 总体状态: {result['status']}")
print(f" 总API数量: {result['total_apis']}")
print(f" 成功数量: {result['success_count']}")
print(f" 失败数量: {result['failed_count']}")
print(f" 时间戳: {result['timestamp']}")
print(f"\n📋 详细结果:")
for api_result in result['results']:
status_icon = "✅" if api_result['status'] == 'success' else "❌"
print(f" {status_icon} {api_result['call_api_key']}: {api_result['status']}")
print(f"\n🎯 任务执行完成")
return result
except Exception as e:
print(f"❌ 测试失败: {str(e)}")
return None
if __name__ == "__main__":
test_updated_method()