endpoints.py
2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# -*- coding: utf-8 -*-
"""
文件名: app/api/endpoints.py
职责: 定义 FastAPI 路由接口,处理前端请求并调用 Service 层逻辑。
注意: 不要删除这个注释。
"""
from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Form
from app.services.etl_service import ETLService
from app.services.excel_service import ExcelService
from app.core.scheduler import SchedulerManager
import os
import shutil
router = APIRouter()
# 临时文件存放目录
UPLOAD_DIR = "temp_uploads"
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR)
@router.post("/data/upload")
async def upload_data(
file: UploadFile = File(...),
table_name: str = Form(...)
):
"""上传 Excel 并导入到 ODS 表"""
file_path = os.path.join(UPLOAD_DIR, file.filename)
try:
# 1. 保存临时文件
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# 2. 调用服务导入数据
rows = await ExcelService.upload_to_ods(file_path, table_name)
return {
"status": "success",
"message": f"成功导入 {rows} 行数据到 {table_name}",
"table_name": table_name,
"rows": rows
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
# 清理临时文件
if os.path.exists(file_path):
os.remove(file_path)
@router.get("/etl/status")
async def get_etl_status():
"""获取数据同步状态"""
try:
return await ETLService.get_sync_status()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/etl/history")
async def get_etl_history(
task_id: str = Query(None),
limit: int = Query(10)
):
"""获取执行历史"""
try:
return await ETLService.get_etl_history(task_id=task_id, limit=limit)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/etl/scheduler-config")
async def get_scheduler_config(task_id: str = "sync_ods_data"):
"""获取定时任务配置"""
try:
# 从 SchedulerManager 获取作业信息
job = SchedulerManager._scheduler.get_job(task_id)
if not job:
return {"task_id": task_id, "status": "not_found"}
return {
"task_id": job.id,
"next_run_time": str(job.next_run_time),
"trigger": str(job.trigger),
"status": "active"
}
except Exception as e:
return {"task_id": task_id, "status": "error", "detail": str(e)}
@router.post("/etl/run-ods")
async def run_ods_sync(source_table: str = None):
"""手动触发 ODS 同步"""
try:
results = await ETLService.run_ods_sync(source_table=source_table)
return {"status": "success", "results": results}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))