Commit 3ed058b0 by 江名洋

feat(api): 新增数据分析与数仓加工接口并优化ETL同步

1 parent 286a9d53
Showing 41 changed files with 682 additions and 33 deletions
......@@ -7,8 +7,8 @@
# 全局
# ============================================================================
APP_ENV=dev
APP_DEBUG=true
APP_PORT=8000
APP_DEBUG=false
APP_PORT=9500
# ============================================================================
# 数据库 (MySQL)
......
No preview for this file type
......@@ -5,13 +5,18 @@
注意: 不要删除这个注释。
"""
from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Form
from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Form, BackgroundTasks
from fastapi.responses import FileResponse
from typing import Optional
from app.services.etl_service import ETLService
from app.services.excel_service import ExcelService
from app.services.analysis_service import AnalysisService
from app.core.scheduler import SchedulerManager
import os
import shutil
import logging
logger = logging.getLogger("app.api")
router = APIRouter()
# 临时文件存放目录
......@@ -21,31 +26,56 @@ if not os.path.exists(UPLOAD_DIR):
@router.post("/data/upload")
async def upload_data(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
table_name: str = Form(...)
table_name: Optional[str] = Form(None),
upload_type: Optional[str] = Form(None),
version_tag: Optional[str] = Form(None)
):
"""上传 Excel 并导入到 ODS 表"""
"""上传 Excel 并导入。支持 ODS 固定表或动态分析表。"""
# 记录接收到的参数,方便调试 422 错误
logger.info(f"Upload request received: filename={file.filename}, table_name={table_name}, upload_type={upload_type}, tag={version_tag}")
file_path = os.path.join(UPLOAD_DIR, file.filename)
try:
# 1. 保存临时文件
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# 2. 调用服务导入数据
# 2. 判断同步模式
if table_name and table_name.strip() != "" and table_name.startswith("ods_"):
# ODS 固定表模式
rows = await ExcelService.upload_to_ods(file_path, table_name)
# 处理完后删除文件
if os.path.exists(file_path): os.remove(file_path)
return {
"status": "success",
"message": f"成功导入 {rows} 行数据到 {table_name}",
"table_name": table_name,
"rows": rows
}
else:
# 动态分析模式
if not upload_type:
if os.path.exists(file_path): os.remove(file_path)
raise HTTPException(status_code=400, detail="智能分析模式下必须选择'分析数据类型'")
# 使用后台任务处理 LLM 分析和导入
background_tasks.add_task(
ExcelService.process_dynamic_upload,
file_path, file.filename, upload_type, version_tag
)
return {
"status": "success",
"message": f"文件 {file.filename} 已上传,正在使用 LLM 进行结构分析并导入后台,请稍后在数据目录查看结果。",
"upload_type": upload_type
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Upload processing failed: {e}", exc_info=True)
if os.path.exists(file_path): os.remove(file_path)
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():
......@@ -85,10 +115,171 @@ async def get_scheduler_config(task_id: str = "sync_ods_data"):
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 同步"""
async def run_ods_sync(background_tasks: BackgroundTasks, source_table: str = None):
"""手动触发 ODS 同步 (后台异步执行)"""
try:
# 使用 BackgroundTasks 异步运行同步任务,防止阻塞主线程
background_tasks.add_task(ETLService.run_ods_sync, source_table, "manual_ods_sync")
return {
"status": "success",
"message": "ODS 同步任务已在后台启动,请查看执行历史获取进度。"
}
except Exception as e:
logger.error(f"Failed to start background ODS sync: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/etl/run-dw")
async def run_dw_sync(
background_tasks: BackgroundTasks,
layer: str = Form(...),
start_date: str = Form(None),
end_date: str = Form(None),
full_sync: str = Form(None)
):
"""手动触发 DWS/DWM/DWA 加工 (后台异步执行)
- 默认增量同步(最近一天)
- full_sync=true 时全量覆盖
- 指定 start_date/end_date 时按日期范围处理
"""
try:
results = await ETLService.run_ods_sync(source_table=source_table)
return {"status": "success", "results": results}
task_id = f"manual_{layer.lower()}_sync"
background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync)
return {
"status": "success",
"message": f"{layer} 加工任务已在后台启动,请查看执行历史获取进度。"
}
except Exception as e:
logger.error(f"Failed to start background {layer} sync: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ==================== 数据分析接口 ====================
@router.get("/analysis/template/{template_type}")
async def download_analysis_template(template_type: str):
"""下载分析模板文件"""
template_map = {
"store": "门店数据-模板.xlsx",
"factory": "主机厂数据-模板.xlsx",
"output": "输出-问界生态系数生态(5.25-6.14).xlsx",
}
filename = template_map.get(template_type)
if not filename:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
# 查找模板文件
search_paths = [
os.path.join("app", "templates", filename),
os.path.join("docs", "test-demos", filename),
]
file_path = None
for p in search_paths:
if os.path.exists(p):
file_path = p
break
if not file_path:
raise HTTPException(status_code=404, detail=f"模板文件不存在: {filename}")
return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
_analysis_store_file = None # 缓存门店文件路径
@router.post("/analysis/upload")
async def analysis_upload(
store_file: Optional[UploadFile] = File(None),
factory_file: Optional[UploadFile] = File(None),
):
"""上传门店数据和主机厂数据"""
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"analysis_store_{store_file.filename}")
with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f)
global _analysis_store_file
_analysis_store_file = file_path
result["messages"].append(f"门店列表已上传: {store_file.filename}")
factory_paths = {}
if factory_file and factory_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"analysis_factory_{factory_file.filename}")
with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f)
# 读取sheet信息
try:
import pandas as pd
sheets = pd.read_excel(file_path, sheet_name=None)
factory_paths["path"] = file_path
factory_paths["sheets"] = list(sheets.keys())
factory_paths["sheet_count"] = len(sheets)
except Exception as e:
factory_paths["error"] = str(e)
result["factory_info"] = factory_paths
result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")
if not result["messages"]:
raise HTTPException(status_code=400, detail="请至少上传一个文件")
return result
@router.post("/analysis/generate")
async def analysis_generate(background_tasks: BackgroundTasks):
"""根据已上传的数据生成生态系数分析报表"""
global _analysis_store_file
if not _analysis_store_file or not os.path.exists(_analysis_store_file):
raise HTTPException(status_code=400, detail="请先上传门店列表文件")
# 查找最近上传的主机厂数据文件
factory_files = sorted(
[f for f in os.listdir(UPLOAD_DIR) if f.startswith("analysis_factory_") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(os.path.join(UPLOAD_DIR, f)),
reverse=True
)
if not factory_files:
raise HTTPException(status_code=400, detail="请先上传主机厂数据文件")
factory_path = os.path.join(UPLOAD_DIR, factory_files[0])
try:
store_df = AnalysisService.read_store_list(_analysis_store_file)
factory_sheets = AnalysisService.read_factory_data(factory_path)
output_path = AnalysisService.build_report(store_df, factory_sheets)
return {
"status": "success",
"message": "分析报表已生成",
"file_path": output_path,
"download_url": "/api/analysis/download",
"store_count": len(store_df),
"factory_sheets": list(factory_sheets.keys()),
"factory_rows": sum(len(v) for v in factory_sheets.values()),
}
except Exception as e:
logger.error(f"Analysis generate failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")
@router.get("/analysis/download")
async def analysis_download():
"""下载生成的分析报表"""
output_dir = "temp_uploads"
output_files = sorted(
[f for f in os.listdir(output_dir) if f.startswith("问界生态系数分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(os.path.join(output_dir, f)),
reverse=True
)
if not output_files:
raise HTTPException(status_code=404, detail="未找到分析报表,请先生成")
file_path = os.path.join(output_dir, output_files[0])
return FileResponse(
file_path,
filename=output_files[0],
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
......@@ -5,28 +5,30 @@
注意: 不要删除这个注释。
"""
import os
from typing import Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
# App Settings
PROJECT_ROOT: str = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
APP_ENV: str = "dev"
APP_DEBUG: bool = True
APP_PORT: int = 8000
APP_DEBUG: bool = False
APP_PORT: int = 9500
# MySQL Settings
DB_HOST: str = "127.0.0.1"
DB_PORT: int = 3306
DB_USER: str = "root"
DB_PASSWORD: str = ""
DB_HOST: str = "192.168.2.155"
DB_PORT: int = 3308
DB_USER: str = "user_jiangmy"
DB_PASSWORD: str = "PYuxMTB1"
DB_NAME: str = "data_analyze"
# Source MySQL Settings
SOURCE_DB_HOST: str = "127.0.0.1"
SOURCE_DB_HOST: str = "192.168.5.23"
SOURCE_DB_PORT: int = 3306
SOURCE_DB_USER: str = "root"
SOURCE_DB_PASSWORD: str = ""
SOURCE_DB_NAME: str = "production"
SOURCE_DB_USER: str = "user_jiangmy"
SOURCE_DB_PASSWORD: str = "VMziLJun"
SOURCE_DB_NAME: str = "dj_smartcarlife"
@property
def database_url(self) -> str:
......@@ -34,7 +36,7 @@ class Settings(BaseSettings):
return f"mysql+pymysql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}?charset=utf8mb4"
# LLM Settings (Qwen)
LLM_QWEN_MODEL: str = "qwen-plus"
LLM_QWEN_MODEL: str = "qwen3.7-plus"
LLM_QWEN_API_KEY: Optional[str] = None
LLM_QWEN_BASE_URL: str = "https://dashscope.aliyuncs.com/compatible-mode/v1"
......@@ -49,7 +51,7 @@ class Settings(BaseSettings):
OSS_ACCESS_KEY_SECRET: Optional[str] = None
OSS_BUCKET_NAME: Optional[str] = None
OSS_ENDPOINT: Optional[str] = None
OSS_PREFIX: str = "multi-webim"
OSS_PREFIX: str = "data-analyze-webui"
OSS_SIGN_EXPIRE_SECONDS: int = 86400
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
......
# -*- coding: utf-8 -*-
"""
文件名: app/core/logging_config.py
职责: 统一日志配置。按模块划分日志文件,控制台彩色输出,文件纯文本输出。
注意: 不要删除这个注释。
"""
import logging
import sys
import os
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from app.core.config import settings
# ── ANSI 颜色码 ──
_RESET = "\033[0m"
_COLORS = {
"DEBUG": "\033[36m", # 青色
"INFO": "\033[32m", # 绿色
"WARNING": "\033[33m", # 黄色
"ERROR": "\033[31m", # 红色
"CRITICAL": "\033[35m", # 紫色
}
_GREY = "\033[90m"
# ── 日志格式(文件用,无颜色) ──
FILE_FORMAT = "%(asctime)s %(levelname)-5s %(message)s [%(filename)s:%(lineno)d]"
DATE_FORMAT = "%H:%M:%S"
class ColoredFormatter(logging.Formatter):
"""控制台彩色格式化器,不修改 record 对象本身"""
def format(self, record: logging.LogRecord) -> str:
# 备份原始信息
orig_levelname = record.levelname
orig_msg = record.msg
color = _COLORS.get(record.levelname, _RESET)
# 仅为本次 format 修改属性
record.levelname = f"{color}{record.levelname}{_RESET}"
if isinstance(record.msg, str):
record.msg = f"{color}{record.msg}{_RESET}"
# 调用父类进行标准格式化(处理 asctime, message 等)
log_line = super().format(record)
# 还原 record,避免影响其他 Handler
record.levelname = orig_levelname
record.msg = orig_msg
# 文件:行号 用灰色
origin = f"{_GREY}[{record.filename}:{record.lineno}]{_RESET}"
plain_origin = f"[{record.filename}:{record.lineno}]"
log_line = log_line.replace(plain_origin, origin)
return log_line
def formatTime(self, record: logging.LogRecord, datefmt: str = None) -> str:
return _GREY + super().formatTime(record, datefmt or DATE_FORMAT) + _RESET
# ── 模块前缀 → 日志文件名 ──
MODULE_LOG_FILES = {
"app.etl": "etl.log",
"app.api": "api.log",
"app.db": "db.log",
"app.scheduler": "scheduler.log",
}
class ModuleFilter(logging.Filter):
"""只放行属于指定模块前缀的日志记录"""
def __init__(self, prefix: str):
super().__init__()
self.prefix = prefix
def filter(self, record) -> bool:
return record.name == self.prefix or record.name.startswith(self.prefix + ".")
class ExcludeModulesFilter(logging.Filter):
"""排除所有已知模块前缀的日志,用于兜底日志文件"""
def __init__(self, prefixes: list[str]):
super().__init__()
self.prefixes = prefixes
def filter(self, record) -> bool:
return not any(
record.name == p or record.name.startswith(p + ".") for p in self.prefixes
)
def setup_logging() -> None:
"""
初始化全局日志系统:
- 按模块写入不同日志文件(logs/ 目录,按天轮转)
- 可选控制台输出
- 抑制第三方库(apscheduler/httpx/aiomysql)的冗余日志
"""
log_dir = Path(settings.PROJECT_ROOT) / settings.LOG_DIR
log_dir.mkdir(parents=True, exist_ok=True)
level = getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO)
root = logging.getLogger()
root.setLevel(level)
root.handlers.clear()
# ── 控制台(彩色) ──
if settings.LOG_CONSOLE:
console = logging.StreamHandler(sys.stdout)
console.setLevel(level)
console.setFormatter(ColoredFormatter(FILE_FORMAT, DATE_FORMAT))
root.addHandler(console)
# ── 各模块独立日志文件(纯文本) ──
for prefix, filename in MODULE_LOG_FILES.items():
fh = TimedRotatingFileHandler(
filename=str(log_dir / filename),
when="midnight",
backupCount=settings.LOG_BACKUP_DAYS,
encoding="utf-8",
)
fh.setLevel(level)
fh.setFormatter(logging.Formatter(FILE_FORMAT, DATE_FORMAT))
fh.addFilter(ModuleFilter(prefix))
root.addHandler(fh)
# ── 全局错误日志(仅记录 ERROR 及以上) ──
error_fh = TimedRotatingFileHandler(
filename=str(log_dir / "error.log"),
when="midnight",
backupCount=settings.LOG_BACKUP_DAYS,
encoding="utf-8",
)
error_fh.setLevel(logging.ERROR)
error_fh.setFormatter(logging.Formatter(FILE_FORMAT, DATE_FORMAT))
root.addHandler(error_fh)
# ── 兜底日志(不属于上述任何模块的) ──
fallback = TimedRotatingFileHandler(
filename=str(log_dir / "other.log"),
when="midnight",
backupCount=settings.LOG_BACKUP_DAYS,
encoding="utf-8",
)
fallback.setLevel(level)
fallback.setFormatter(logging.Formatter(FILE_FORMAT, DATE_FORMAT))
fallback.addFilter(ExcludeModulesFilter(list(MODULE_LOG_FILES.keys())))
root.addHandler(fallback)
# ── 抑制第三方库日志 ──
for lib in ("apscheduler", "httpx", "aiomysql", "urllib3", "uvicorn", "fastapi"):
logging.getLogger(lib).setLevel(logging.WARNING)
......@@ -30,10 +30,10 @@ class SchedulerManager:
if cls._scheduler is None:
cls._scheduler = AsyncIOScheduler()
# 1. ODS 同步任务 (每 3 分钟执行一次,带 3s 抖动,模仿用户参考)
# 1. ODS 同步任务 (每 30 分钟执行一次,带 3s 抖动,模仿用户参考)
cls._scheduler.add_job(
cls.sync_ods_task,
IntervalTrigger(minutes=3, jitter=3),
IntervalTrigger(minutes=30, jitter=3),
id="sync_ods_data",
max_instances=1,
replace_existing=True
......@@ -56,8 +56,9 @@ class SchedulerManager:
async def stop(cls):
"""停止定时任务调度器"""
if cls._scheduler and cls._scheduler.running:
cls._scheduler.shutdown()
logger.info("[Scheduler] APScheduler shut down.")
# wait=False 表示不等待正在运行的任务完成,立即停止调度器
cls._scheduler.shutdown(wait=False)
logger.info("[Scheduler] APScheduler shut down (immediate).")
@classmethod
async def sync_ods_task(cls):
......
# -*- coding: utf-8 -*-
"""
文件名: app/services/llm_service.py
职责: LLM 业务逻辑,负责调用 Qwen 3.7-Plus 等模型进行 Excel 表结构分析和逻辑识别。
注意: 不要删除这个注释。
"""
import json
import logging
import httpx
from typing import Dict, Any, List
from app.core.config import settings
logger = logging.getLogger("app.llm")
class LLMService:
@classmethod
async def analyze_excel_schema(cls, sheet_name: str, headers: List[List[Any]], sample_data: List[Dict[str, Any]], upload_type: str) -> Dict[str, Any]:
"""
使用 Qwen 3.7-Plus 分析 Excel 表结构。
"""
if not settings.LLM_QWEN_API_KEY:
logger.warning("LLM_QWEN_API_KEY is not set, skipping LLM analysis.")
return {}
prompt = f"""
你是一个高级数据工程师。请分析以下 Excel 表格结构并返回一个 JSON 格式的数据库表定义。
上传类型: {upload_type}
Sheet 名称: {sheet_name}
原始表头 (可能包含多行): {json.dumps(headers, ensure_ascii=False)}
示例数据 (前几行): {json.dumps(sample_data, ensure_ascii=False)}
请识别:
1. 实际的业务列名(处理多行表头,合并成有意义的单个列名)。
2. 数据类型 (VARCHAR, DECIMAL, INT, DATETIME 等)。
3. 列注释 (中文描述)。
4. 分析周期 (如果是日报/周报/月报,请识别具体的周期字段)。
返回 JSON 格式必须如下:
{{
"table_name": "建议的表名(小写下划线)",
"analysis_period_col": "周期字段名(如果没有则为 null)",
"columns": [
{{
"name": "字段名",
"type": "SQL类型",
"comment": "描述",
"is_nullable": true
}}
]
}}
仅返回 JSON 内容,不要包含任何 Markdown 格式。
"""
try:
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(
f"{settings.LLM_QWEN_BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {settings.LLM_QWEN_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": settings.LLM_QWEN_MODEL,
"messages": [
{"role": "system", "content": "You are a helpful data engineering assistant."},
{"role": "user", "content": prompt}
],
"temperature": 0.1
}
)
if response.status_code != 200:
logger.error(f"LLM API Error: {response.status_code} - {response.text}")
return {}
result = response.json()
content = result['choices'][0]['message']['content'].strip()
# 去除可能的 markdown 代码块标记
if content.startswith("```json"):
content = content[7:-3].strip()
elif content.startswith("```"):
content = content[3:-3].strip()
return json.loads(content)
except Exception as e:
logger.error(f"Failed to call LLM for schema analysis: {e}")
return {}
......@@ -118,3 +118,78 @@ h2 {
margin-bottom: 20px;
color: #2c3e50;
}
/* 弹窗样式 (Modal) */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
}
.modal-content {
background-color: white;
margin: 5% auto;
padding: 20px;
border-radius: 8px;
width: 70%;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #eee;
padding-bottom: 15px;
margin-bottom: 15px;
}
.close-btn {
font-size: 28px;
font-weight: bold;
cursor: pointer;
color: #999;
}
.close-btn:hover {
color: #333;
}
/* 详情表格样式 */
.detail-table {
width: 100%;
border-collapse: collapse;
}
.detail-table th, .detail-table td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #f0f0f0;
}
.detail-table th {
background-color: #fafafa;
color: #555;
font-weight: 600;
}
.detail-table tr:hover {
background-color: #fafafa;
}
.status-tag {
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
}
.status-success { background-color: #f6ffed; border: 1px solid #b7eb8f; color: #52c41a; }
.status-failed { background-color: #fff1f0; border: 1px solid #ffa39e; color: #f5222d; }
.status-info { background-color: #e6f7ff; border: 1px solid #91d5ff; color: #1890ff; }
No preview for this file type
No preview for this file type
File mode changed
File mode changed
14:00:52 ERROR [X] DWS Sync failed for task_id=manual_dws_sync: (1054, "Unknown column 'report_date' in 'where clause'") [etl_service.py:326]
Traceback (most recent call last):
File "D:\work1\data-analyze-webui\app\services\etl_service.py", line 291, in run_dw_sync
cur.execute(f"DELETE FROM `{table_name}` WHERE report_date BETWEEN %s AND %s", (start_date, end_date))
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 157, in execute
result = self._query(query)
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
~~~~~~~~~~^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 575, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 826, in _read_query_result
result.read()
~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 1203, in read
first_packet = self.connection._read_packet()
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 782, in _read_packet
packet.raise_for_error()
~~~~~~~~~~~~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\protocol.py", line 219, in raise_for_error
err.raise_mysql_exception(self._data)
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\err.py", line 150, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.OperationalError: (1054, "Unknown column 'report_date' in 'where clause'")
14:07:54 ERROR [X] ODS Sync failed for task_id=manual_ods_sync: (1048, "Column 'merchant_id' cannot be null") [etl_service.py:220]
Traceback (most recent call last):
File "D:\work1\data-analyze-webui\app\services\etl_service.py", line 177, in run_ods_sync
cur.executemany(upsert_sql, data_tuples)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 186, in executemany
return self._do_execute_many(
~~~~~~~~~~~~~~~~~~~~~^
q_prefix,
^^^^^^^^^
...<4 lines>...
self._get_db().encoding,
^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 219, in _do_execute_many
rows += self.execute(sql + postfix)
~~~~~~~~~~~~^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 157, in execute
result = self._query(query)
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
~~~~~~~~~~^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 575, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 826, in _read_query_result
result.read()
~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 1203, in read
first_packet = self.connection._read_packet()
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 782, in _read_packet
packet.raise_for_error()
~~~~~~~~~~~~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\protocol.py", line 219, in raise_for_error
err.raise_mysql_exception(self._data)
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\err.py", line 150, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.IntegrityError: (1048, "Column 'merchant_id' cannot be null")
14:49:20 ERROR Failed to call LLM for schema analysis: [llm_service.py:90]
14:50:21 ERROR Failed to call LLM for schema analysis: [llm_service.py:90]
14:50:21 ERROR Failed to process dynamic upload: Object of type datetime is not JSON serializable [excel_service.py:105]
Traceback (most recent call last):
File "D:\work1\data-analyze-webui\app\services\excel_service.py", line 73, in process_dynamic_upload
schema = await LLMService.analyze_excel_schema(sheet, headers_raw, sample_data_raw, upload_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\work1\data-analyze-webui\app\services\llm_service.py", line 31, in analyze_excel_schema
原始表头 (可能包含多行): {json.dumps(headers, ensure_ascii=False)}
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\json\__init__.py", line 242, in dumps
**kw).encode(obj)
~~~~~~^^^^^
File "D:\Python313\Lib\json\encoder.py", line 202, in encode
chunks = self.iterencode(o, _one_shot=True)
File "D:\Python313\Lib\json\encoder.py", line 263, in iterencode
return _iterencode(o, 0)
File "D:\Python313\Lib\json\encoder.py", line 182, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
f'is not JSON serializable')
TypeError: Object of type datetime is not JSON serializable
This diff could not be displayed because it is too large.
......@@ -7,6 +7,7 @@
import uvicorn
import os
import asyncio
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
......@@ -14,6 +15,10 @@ from contextlib import asynccontextmanager
from app.core.scheduler import SchedulerManager
from app.core.config import settings
from app.api.endpoints import router as api_router
from app.core.logging_config import setup_logging
# 初始化日志
setup_logging()
# 基础目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
......@@ -27,7 +32,13 @@ async def lifespan(app: FastAPI):
yield
# 关闭时执行
print("[*] Stopping Data Analyze WebUI...")
await SchedulerManager.stop()
try:
# 强制设置停止超时,防止由于任务阻塞导致进程无法退出
await asyncio.wait_for(SchedulerManager.stop(), timeout=5.0)
except asyncio.TimeoutError:
print("[!] Scheduler stop timed out, forcing exit.")
except Exception as e:
print(f"[!] Error during stop: {e}")
app = FastAPI(
title="问界门店运营数据分析平台",
......
......@@ -14,6 +14,8 @@ CREATE TABLE IF NOT EXISTS `_sync_meta` (
`source_table` VARCHAR(128) NOT NULL COMMENT '源表名',
`target_table` VARCHAR(128) NOT NULL COMMENT '目标表名',
`last_sync_time` DATETIME DEFAULT NULL COMMENT '上次同步时间(源库updated_date最大值)',
`last_sync_start_time` DATETIME DEFAULT NULL COMMENT '本次同步起始时间(上次last_sync_time)',
`last_sync_end_time` DATETIME DEFAULT NULL COMMENT '本次同步结束时间(本次源库updated_date最大值)',
`last_sync_rows` INT DEFAULT 0 COMMENT '上次同步行数',
`sync_mode` VARCHAR(16) DEFAULT 'full' COMMENT '同步模式: full/incremental',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
......@@ -32,12 +34,43 @@ CREATE TABLE IF NOT EXISTS `_etl_history` (
`status` VARCHAR(16) DEFAULT 'running' COMMENT '状态: running/success/failed',
`params` TEXT DEFAULT NULL COMMENT '执行参数(JSON)',
`result_info` TEXT DEFAULT NULL COMMENT '执行结果/错误信息',
`tables_involved` TEXT DEFAULT NULL COMMENT '涉及的表名(逗号分隔)',
`data_range` VARCHAR(128) DEFAULT NULL COMMENT '数据时间范围',
`rows_affected` INT DEFAULT 0 COMMENT '影响行数',
PRIMARY KEY (`id`),
INDEX idx_task_time (task_id, start_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ETL执行历史记录';
-- ============================================================================
-- 0.2 数据上传记录表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `_upload_files` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
`filename` VARCHAR(256) NOT NULL COMMENT '文件名',
`file_path` VARCHAR(512) NOT NULL COMMENT '存储路径',
`upload_type` VARCHAR(64) NOT NULL COMMENT '上传类型(门店列表/主机厂/赔付方案)',
`version_tag` VARCHAR(64) DEFAULT NULL COMMENT '版本标识(如 202406_v1)',
`sheet_names` TEXT DEFAULT NULL COMMENT '包含的Sheet名(JSON)',
`analysis_period` VARCHAR(128) DEFAULT NULL COMMENT '分析周期(由LLM识别)',
`status` VARCHAR(16) DEFAULT 'uploaded' COMMENT '状态: uploaded/analyzing/completed/failed',
`llm_schema` TEXT DEFAULT NULL COMMENT 'LLM识别的表结构(JSON)',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX idx_type_version (upload_type, version_tag)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='上传文件及版本管理';
-- ============================================================================
-- 0.3 动态表元数据
-- ============================================================================
CREATE TABLE IF NOT EXISTS `_dynamic_table_meta` (
`table_name` VARCHAR(128) NOT NULL COMMENT '生成的数据库表名',
`upload_type` VARCHAR(64) NOT NULL COMMENT '上传类型',
`schema_json` TEXT NOT NULL COMMENT '表结构定义',
`last_updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`table_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='动态生成的表元数据';
-- ============================================================================
-- 1. ODS 层 — 贴源层
-- ============================================================================
......
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!