fix: 统一使用 task_uuid 字段替换 task_id

- 前端界面显示和消息提示中 task_id 改为 task_uuid
- API 调用和文件下载命名使用 task_uuid
- 新增后端推理任务清理脚本,支持按状态、时间清理和查看任务列表
This commit is contained in:
yilv committed 2026-04-06 21:42:05 +08:00
1 parent 47d583ad92
commit 9039cdc222
2 files changed
+321 -7

No files matched your search

+314
View File
@@ -0,0 +1,314 @@
"""
清理所有推理任务脚本
用于清理所有推理任务(包括 queued、running、completed、failed 状态)
警告:此操作不可逆,请谨慎使用!
"""
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 从环境变量读取配置,默认为 'default'
config_name = os.environ.get('FLASK_CONFIG', 'default')
from app import create_app, db
from app.models import InferenceTask, InferenceTaskResult
from datetime import datetime
def cleanup_all_tasks(confirm=True):
"""
清理所有推理任务及关联的结果
Args:
confirm: 是否需要确认
"""
app = create_app(config_name)
with app.app_context():
# 统计各状态任务数量
all_tasks = InferenceTask.query.all()
status_count = {}
for task in all_tasks:
status_count[task.status] = status_count.get(task.status, 0) + 1
print("=" * 60)
print("推理任务清理脚本")
print("=" * 60)
print(f"\n当前数据库中任务统计:")
print(f" 总任务数:{len(all_tasks)}")
for status, count in sorted(status_count.items()):
print(f" - {status}: {count} 个")
# 统计关联的结果数量
result_count = InferenceTaskResult.query.count()
print(f"\n关联的推理结果数:{result_count}")
if confirm:
print("\n" + "!" * 60)
print("警告:此操作将删除所有推理任务和结果,且不可恢复!")
print("!" * 60)
confirm_text = input(f"\n请输入 'YES' 确认清理所有任务:")
if confirm_text != 'YES':
print("已取消操作")
return
print("\n开始清理...")
# 先删除关联的结果(外键约束)
print("正在删除推理结果...")
deleted_results = 0
batch_size = 1000
while True:
results = InferenceTaskResult.query.limit(batch_size).all()
if not results:
break
for r in results:
db.session.delete(r)
db.session.commit()
deleted_results += len(results)
print(f" 已删除 {deleted_results} 条结果...")
# 删除所有任务
print("正在删除推理任务...")
deleted_tasks = 0
for task in all_tasks:
db.session.delete(task)
deleted_tasks += 1
if deleted_tasks % 100 == 0:
print(f" 已删除 {deleted_tasks} 个任务...")
db.session.commit()
print("\n" + "=" * 60)
print("清理完成!")
print(f" - 删除任务数:{deleted_tasks}")
print(f" - 删除结果数:{deleted_results}")
print("=" * 60)
def cleanup_by_status(status_list, confirm=True):
"""
按状态清理任务
Args:
status_list: 要清理的状态列表,如 ['queued', 'running']
confirm: 是否需要确认
"""
app = create_app(config_name)
with app.app_context():
# 查询指定状态的任务
tasks = InferenceTask.query.filter(InferenceTask.status.in_(status_list)).all()
print("=" * 60)
print("按状态清理推理任务")
print("=" * 60)
print(f"\n将清理以下状态的任务:{', '.join(status_list)}")
print(f" 任务数量:{len(tasks)}")
# 统计关联的结果数量
task_ids = [t.id for t in tasks]
results = InferenceTaskResult.query.filter(
InferenceTaskResult.task_id.in_(task_ids)
).all()
print(f" 关联结果数:{len(results)}")
if confirm:
confirm_text = input(f"\n请输入 'YES' 确认清理:")
if confirm_text != 'YES':
print("已取消操作")
return
print("\n开始清理...")
# 先删除关联的结果
deleted_results = 0
for result in results:
db.session.delete(result)
deleted_results += 1
# 删除任务
deleted_tasks = 0
for task in tasks:
db.session.delete(task)
deleted_tasks += 1
db.session.commit()
print("\n" + "=" * 60)
print("清理完成!")
print(f" - 删除任务数:{deleted_tasks}")
print(f" - 删除结果数:{deleted_results}")
print("=" * 60)
def cleanup_old_tasks(days_threshold=30, confirm=True):
"""
清理超过指定天数的历史任务
Args:
days_threshold: 超过多少天的任务视为历史任务
confirm: 是否需要确认
"""
app = create_app(config_name)
with app.app_context():
from datetime import datetime, timedelta
threshold = datetime.utcnow() - timedelta(days=days_threshold)
# 查询超过阈值的任务
old_tasks = InferenceTask.query.filter(
InferenceTask.created_at < threshold
).all()
print("=" * 60)
print(f"清理 {days_threshold} 天前的历史任务")
print("=" * 60)
print(f"\n将清理 {days_threshold} 天前的任务")
print(f" 阈值日期:{threshold.strftime('%Y-%m-%d %H:%M:%S')}")
print(f" 任务数量:{len(old_tasks)}")
# 统计关联的结果数量
task_ids = [t.id for t in old_tasks]
results = InferenceTaskResult.query.filter(
InferenceTaskResult.task_id.in_(task_ids)
).all()
print(f" 关联结果数:{len(results)}")
if confirm:
confirm_text = input(f"\n请输入 'YES' 确认清理:")
if confirm_text != 'YES':
print("已取消操作")
return
print("\n开始清理...")
# 先删除关联的结果
deleted_results = 0
for result in results:
db.session.delete(result)
deleted_results += 1
# 删除任务
deleted_tasks = 0
for task in old_tasks:
db.session.delete(task)
deleted_tasks += 1
db.session.commit()
print("\n" + "=" * 60)
print("清理完成!")
print(f" - 删除任务数:{deleted_tasks}")
print(f" - 删除结果数:{deleted_results}")
print("=" * 60)
def show_task_list():
"""
显示当前所有任务列表(不执行删除)
"""
app = create_app(config_name)
with app.app_context():
tasks = InferenceTask.query.order_by(InferenceTask.created_at.desc()).limit(50).all()
print("=" * 80)
print("当前推理任务列表(最近 50 条)")
print("=" * 80)
print(f"{'任务 UUID':<40} {'状态':<12} {'创建时间':<22} {'患者数':<8}")
print("-" * 80)
for task in tasks:
patient_count = len(task.folders)
created = task.created_at.strftime('%Y-%m-%d %H:%M:%S') if task.created_at else 'N/A'
print(f"{task.task_uuid:<40} {task.status:<12} {created:<22} {patient_count:<8}")
print("-" * 80)
# 统计总数
total = InferenceTask.query.count()
print(f"总任务数:{total}")
if __name__ == '__main__':
if len(sys.argv) < 2:
print("""
推理任务清理脚本
用法:
python cleanup_all_inference_tasks.py <命令> [选项]
命令:
all 清理所有任务(包括 queued/running/completed/failed)
status <状态> 清理指定状态的任务(如:queued, running, completed, failed)
old [天数] 清理超过指定天数的历史任务(默认 30 天)
list 显示当前任务列表(不执行删除)
help 显示帮助信息
示例:
python cleanup_all_inference_tasks.py all # 清理所有任务
python cleanup_all_inference_tasks.py status queued # 清理所有排队中的任务
python cleanup_all_inference_tasks.py old 7 # 清理 7 天前的任务
python cleanup_all_inference_tasks.py list # 查看任务列表
""")
sys.exit(0)
command = sys.argv[1].lower()
if command == 'all':
cleanup_all_tasks(confirm=True)
elif command == 'status':
if len(sys.argv) < 3:
print("错误:请指定要清理的状态(queued/running/completed/failed)")
sys.exit(1)
status = sys.argv[2].lower()
valid_statuses = ['queued', 'running', 'completed', 'failed']
if status not in valid_statuses:
print(f"错误:无效的状态 '{status}',有效状态:{', '.join(valid_statuses)}")
sys.exit(1)
cleanup_by_status([status], confirm=True)
elif command == 'old':
days = 30
if len(sys.argv) >= 3:
try:
days = int(sys.argv[2])
except ValueError:
print("错误:天数必须是整数")
sys.exit(1)
cleanup_old_tasks(days_threshold=days, confirm=True)
elif command == 'list':
show_task_list()
elif command == 'help':
print("""
推理任务清理脚本
用法:
python cleanup_all_inference_tasks.py <命令> [选项]
命令:
all 清理所有任务(包括 queued/running/completed/failed)
status <状态> 清理指定状态的任务(如:queued, running, completed, failed)
old [天数] 清理超过指定天数的历史任务(默认 30 天)
list 显示当前任务列表(不执行删除)
help 显示帮助信息
示例:
python cleanup_all_inference_tasks.py all # 清理所有任务
python cleanup_all_inference_tasks.py status queued # 清理所有排队中的任务
python cleanup_all_inference_tasks.py old 7 # 清理 7 天前的任务
python cleanup_all_inference_tasks.py list # 查看任务列表
""")
else:
print(f"错误:未知命令 '{command}'")
print("使用 'python cleanup_all_inference_tasks.py help' 查看帮助")
sys.exit(1)
+7 -7
View File
@@ -200,7 +200,7 @@
<!-- 推理任务列表对话框 -->
<el-dialog v-model="taskListVisible" title="推理任务列表" width="900px">
<el-table :data="taskList" style="width: 100%" v-loading="taskListLoading">
<el-table-column prop="task_id" label="任务 ID" width="280" show-overflow-tooltip />
<el-table-column prop="task_uuid" label="任务 ID" width="280" show-overflow-tooltip />
<el-table-column prop="status" label="状态" width="120">
<template #default="scope">
<el-tag :type="getStatusType(scope.row.status)">
@@ -468,12 +468,12 @@ const confirmInference = async () => {
submitting.value = true
try {
const res = await api.post('/admin/inference-data/run', inferenceForm.value)
ElMessage.success(`推理任务已提交,任务 ID: ${res.task_id}`)
ElMessage.success(`推理任务已提交,任务 ID: ${res.task_uuid}`)
inferenceVisible.value = false
// 显示进度对话框
currentTask.value = {
task_id: res.task_id,
task_uuid: res.task_uuid,
status: 'queued',
progress: {
current_patient: 0,
@@ -488,7 +488,7 @@ const confirmInference = async () => {
progressVisible.value = true
// 开始轮询进度
startProgressPolling(res.task_id)
startProgressPolling(res.task_uuid)
} catch (error) {
if (error.response?.status === 409) {
ElMessage.warning(error.response.data.msg)
@@ -605,13 +605,13 @@ const fetchTaskList = async () => {
// 查看任务详情
const viewTaskDetail = async (task) => {
try {
const res = await api.get(`/admin/inference-data/tasks/${task.task_id}`)
const res = await api.get(`/admin/inference-data/tasks/${task.task_uuid}`)
currentTask.value = res.data
progressVisible.value = true
// 如果任务正在运行,开始轮询
if (res.status === 'running' || res.status === 'queued') {
startProgressPolling(task.task_id)
startProgressPolling(task.task_uuid)
}
} catch (error) {
ElMessage.error('获取任务详情失败')
@@ -639,7 +639,7 @@ const exportResults = () => {
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = `inference_${currentTask.value.task_id}_${new Date().toISOString().split('T')[0]}.csv`
link.download = `inference_${currentTask.value.task_uuid}_${new Date().toISOString().split('T')[0]}.csv`
link.click()
}