改为遍历配置文件

This commit is contained in:
mark.tian
2025-12-09 15:59:58 +08:00
parent d10c403ddc
commit f91c540bde
2 changed files with 22 additions and 80 deletions

View File

@@ -2,64 +2,6 @@
# API配置 # API配置
API_CONFIG = { API_CONFIG = {
# 主要API接口
'main_api': {
'url': 'https://jsonplaceholder.typicode.com/posts',
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'User-Agent': 'Celery-Task/1.0'
},
'timeout': 30,
'body': {
'title': '每日定时任务',
'body': '这是通过配置文件设置的请求体数据',
'userId': 1
}
},
# 备用API接口
'backup_api': {
'url': 'https://jsonplaceholder.typicode.com/comments',
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'User-Agent': 'Celery-Task/1.0'
},
'timeout': 30,
'body': {
'name': '备用任务',
'email': 'backup@example.com',
'body': '这是备用API的请求体'
}
},
# 健康检查API
'health_check': {
'url': 'https://jsonplaceholder.typicode.com/posts/1',
'method': 'GET',
'headers': {
'User-Agent': 'Celery-Task/1.0'
},
'timeout': 10,
'body': {} # GET请求通常不需要body,但可以设置查询参数
},
# GET请求示例API
'get_api': {
'url': 'https://jsonplaceholder.typicode.com/posts',
'method': 'GET',
'headers': {
'User-Agent': 'Celery-Task/1.0'
},
'timeout': 30,
'body': {
'userId': 1, # 这将作为查询参数
'limit': 10
}
},
# PUT请求示例API
'put_api': { 'put_api': {
'url': 'https://jsonplaceholder.typicode.com/posts/1', 'url': 'https://jsonplaceholder.typicode.com/posts/1',
'method': 'PUT', 'method': 'PUT',

View File

@@ -9,16 +9,16 @@ logger = logging.getLogger(__name__)
@app.task(bind=True, max_retries=None) @app.task(bind=True, max_retries=None)
def invoke_call_api_task(self): def invoke_call_api_task(self):
"""遍历API配置文件中的所有API配置并调用接口""" """遍历API配置文件中的所有API信息并调用接口"""
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信息
results = [] results = []
success_count = 0 success_count = 0
@@ -32,7 +32,7 @@ def invoke_call_api_task(self):
payload = call_config['body'] payload = call_config['body']
try: try:
logger.info(f"正在调用呼叫任务API: {method} {call_url}") logger.info(f"正在调用任务API: {method} {call_url}")
# 根据method选择请求方式 # 根据method选择请求方式
if method == 'POST': if method == 'POST':
@@ -53,14 +53,14 @@ def invoke_call_api_task(self):
except: except:
result_data = {'response': response.text} result_data = {'response': response.text}
logger.info(f"呼叫任务API调用成功,响应数据: {result_data}") logger.info(f"任务API调用成功,响应数据: {result_data}")
print(f"[{current_time}] ✅ 呼叫任务API成功 ({api_key}) - {method} {call_url}") print(f"[{current_time}] ✅ 任务API成功 ({api_key}) - {method} {call_url}")
success_count += 1 success_count += 1
results.append({ results.append({
'call_api_key': api_key, 'call_api_key': api_key,
'status': 'success', 'status': 'success',
'message': f'呼叫任务API调用成功 ({method})', 'message': f'任务API调用成功 ({method})',
'response': result_data, 'response': result_data,
'timestamp': current_time, 'timestamp': current_time,
'retry_count': getattr(self.request, 'retries', 0) 'retry_count': getattr(self.request, 'retries', 0)
@@ -69,28 +69,28 @@ def invoke_call_api_task(self):
# 需要重试的状态码 # 需要重试的状态码
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}) - {api_key} - 状态码: {response.status_code}") 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}")) raise self.retry(countdown=retry_delay, exc=Exception(f"任务API失败,状态码: {response.status_code}"))
else: else:
logger.error(f"呼叫任务API失败,已达到最大重试次数: {max_retries}") logger.error(f"任务API失败,已达到最大重试次数: {max_retries}")
print(f"[{current_time}] ❌ 呼叫任务API失败,已达到最大重试次数 - {api_key} - 状态码: {response.status_code}") print(f"[{current_time}] ❌ 任务API失败,已达到最大重试次数 - {api_key} - 状态码: {response.status_code}")
results.append({ results.append({
'call_api_key': api_key, 'call_api_key': api_key,
'status': 'failed', 'status': 'failed',
'message': f'呼叫任务API失败,已达到最大重试次数: {max_retries}', 'message': f'任务API失败,已达到最大重试次数: {max_retries}',
'response': response.text, 'response': response.text,
'timestamp': current_time, 'timestamp': current_time,
'retry_count': current_retry + 1 'retry_count': current_retry + 1
}) })
else: else:
# 其他失败状态码,不重试 # 其他失败状态码,不重试
logger.error(f"呼叫任务API失败,状态码: {response.status_code}, 响应: {response.text}") logger.error(f"任务API失败,状态码: {response.status_code}, 响应: {response.text}")
print(f"[{current_time}] ❌ 呼叫任务API失败 - {api_key} - 状态码: {response.status_code}") print(f"[{current_time}] ❌ 任务API失败 - {api_key} - 状态码: {response.status_code}")
results.append({ results.append({
'call_api_key': api_key, 'call_api_key': api_key,
'status': 'failed', 'status': 'failed',
'message': f'呼叫任务API失败,状态码: {response.status_code}', 'message': f'任务API失败,状态码: {response.status_code}',
'response': response.text, 'response': response.text,
'timestamp': current_time, 'timestamp': current_time,
'retry_count': getattr(self.request, 'retries', 0) 'retry_count': getattr(self.request, 'retries', 0)
@@ -100,16 +100,16 @@ def invoke_call_api_task(self):
# 网络异常,需要重试 # 网络异常,需要重试
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}) - {api_key} - 异常: {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异常,已达到最大重试次数 - {api_key} - 异常: {str(e)}") print(f"[{current_time}] ❌ 任务API异常,已达到最大重试次数 - {api_key} - 异常: {str(e)}")
results.append({ results.append({
'call_api_key': api_key, 'call_api_key': api_key,
'status': 'error', 'status': 'error',
'message': f'呼叫任务API异常,已达到最大重试次数: {max_retries}', 'message': f'任务API异常,已达到最大重试次数: {max_retries}',
'error': str(e), 'error': str(e),
'timestamp': current_time, 'timestamp': current_time,
'retry_count': current_retry + 1 'retry_count': current_retry + 1
@@ -117,7 +117,7 @@ def invoke_call_api_task(self):
# 汇总结果 # 汇总结果
total_count = len(results) total_count = len(results)
logger.info(f"遍历API配置文件执行完成 - 成功: {success_count}/{total_count}") logger.info(f"遍历API配置文件完成 - 成功: {success_count}/{total_count}")
print(f"[{current_time}] 📊 任务汇总 - 成功: {success_count}/{total_count}") print(f"[{current_time}] 📊 任务汇总 - 成功: {success_count}/{total_count}")
return { return {