main.py
2.59 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
# -*- coding: utf-8 -*-
"""
文件名: main.py
职责: 项目启动入口,初始化 FastAPI 应用,挂载路由和静态资源。
注意: 不要删除这个注释。
"""
import uvicorn
import os
import asyncio
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
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__))
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时执行
print("[*] Starting Data Analyze WebUI...")
# 启动定时任务调度器
await SchedulerManager.start()
yield
# 关闭时执行
print("[*] Stopping Data Analyze WebUI...")
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="问界门店运营数据分析平台",
description="支持 ODS/DWS/DWM/DWA 各层数据同步任务及分析模版展示",
version="1.0.0",
lifespan=lifespan,
root_path="/daw",
)
# 挂载静态文件
app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "app/static")), name="static")
# 配置模板引擎
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))
# 注册 API 路由
app.include_router(api_router, prefix="/api")
# 页面路由映射:路径 → 模板文件名
PAGE_ROUTES = {
"/": "index.html",
"/ods": "ods.html",
"/dw": "dw.html",
"/analysis": "analysis.html",
"/harmony": "harmony.html",
}
def _page_handler(template_name: str):
"""闭包工厂:为指定模板生成页面处理函数"""
async def handler(request: Request):
return templates.TemplateResponse(request=request, name=template_name, context={})
return handler
for path, tpl in PAGE_ROUTES.items():
app.get(path)(_page_handler(tpl))
@app.get("/api/health")
async def health():
"""健康检查接口"""
return {"status": "ok", "message": "Welcome to Data Analyze WebUI API"}
if __name__ == "__main__":
# 端口指定 9500
uvicorn.run(
"main:app",
host="0.0.0.0",
port=9500,
reload=settings.APP_DEBUG
)