更新时间 2026-10-11 17:28
This commit is contained in:
@@ -0,0 +1,271 @@
|
||||
"""
|
||||
药品任务监控看板 —— FastAPI 后端
|
||||
|
||||
统计口径:
|
||||
1. 每个批次的任务总量:按 batch 分组统计总任务数、已完成数、未完成数、完成率
|
||||
2. 每小时完成量:只统计今天(DATE(update_time) = CURDATE()),
|
||||
按 update_time 的小时切片聚合,仅计 is_ok = '1' 的已完成任务
|
||||
|
||||
未完成定义:is_ok 为 '0' 或 NULL
|
||||
|
||||
已剔除的数据:is_ok = '99' 既不算完成也不算未完成,直接从统计分母中排除
|
||||
|
||||
缓存策略:
|
||||
- 统计结果缓存 30 分钟,到期后下次请求自动重算
|
||||
- 前端传 force=1 时跳过缓存立即重算(手动刷新)
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
from fastapi import FastAPI, Query
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
# ---------------------------------------------------------------- 数据库配置
|
||||
DB_CONFIG = {
|
||||
"host": "192.168.5.5",
|
||||
"port": 3306,
|
||||
"user": "root",
|
||||
"password": "Aliyun@7646!",
|
||||
"database": "project_drug_detail",
|
||||
"charset": "utf8mb4",
|
||||
"connect_timeout": 10,
|
||||
"read_timeout": 120, # 聚合查询在数据量大时可能较慢
|
||||
"cursorclass": pymysql.cursors.Cursor,
|
||||
}
|
||||
|
||||
CACHE_TTL = 30 * 60 # 缓存有效期:30 分钟
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
STATIC_DIR = BASE_DIR / "static"
|
||||
|
||||
app = FastAPI(title="监控看板", version="1.0.0")
|
||||
|
||||
# ---------------------------------------------------------------- 缓存实现
|
||||
_cache = {"data": None, "ts": 0.0}
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_conn():
|
||||
"""获取数据库连接,确保归还。"""
|
||||
conn = pymysql.connect(**DB_CONFIG)
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def fetch_batch_stats(cur):
|
||||
"""
|
||||
每个批次的任务总量统计。
|
||||
|
||||
is_ok = '1' -> 已完成
|
||||
is_ok = '0' -> 未完成
|
||||
is_ok 为 NULL -> 未完成
|
||||
is_ok = '99' 或其他值 -> 忽略,不计入任何统计
|
||||
|
||||
因此分母 total 只统计 is_ok IN ('1','0') 或 is_ok IS NULL 的行。
|
||||
"""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
batch,
|
||||
COUNT(*) AS total,
|
||||
COUNT(CASE WHEN is_ok = '1' THEN 1 END) AS done,
|
||||
COUNT(CASE WHEN is_ok IS NULL OR is_ok = '0' THEN 1 END) AS undone,
|
||||
MIN(create_time) AS first_create,
|
||||
MAX(update_time) AS last_update
|
||||
FROM drug_detail_list
|
||||
WHERE batch IS NOT NULL AND batch <> ''
|
||||
AND (is_ok IN ('0', '1') OR is_ok IS NULL) -- 排除 '99' 等无效状态
|
||||
GROUP BY batch
|
||||
ORDER BY batch DESC
|
||||
"""
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
cols = ["batch", "total", "done", "undone", "first_create", "last_update"]
|
||||
|
||||
result = []
|
||||
for row in rows:
|
||||
item = dict(zip(cols, row))
|
||||
total = int(item["total"] or 0)
|
||||
done = int(item["done"] or 0)
|
||||
item["total"] = total
|
||||
item["done"] = done
|
||||
item["undone"] = int(item["undone"] or 0)
|
||||
item["rate"] = round(done / total * 100, 1) if total else 0.0
|
||||
# datetime 转字符串,方便前端直接展示
|
||||
for k in ("first_create", "last_update"):
|
||||
item[k] = item[k].strftime("%Y-%m-%d %H:%M:%S") if item[k] else None
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def fetch_hourly_stats(cur):
|
||||
"""
|
||||
今日每小时完成量。
|
||||
|
||||
按 update_time 的小时切片聚合,只计 is_ok = '1'。
|
||||
同时按批次拆出明细,供前端做堆叠/切换。
|
||||
返回:
|
||||
hours —— 0~23 的完整小时轴(缺失小时补 0,避免折线断裂)
|
||||
total_by_hour —— 每个小时的总完成量
|
||||
by_batch —— {批次: [每小时完成量 * 24]}
|
||||
"""
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch, HOUR(update_time) AS h, COUNT(*) AS cnt
|
||||
FROM drug_detail_list
|
||||
WHERE is_ok = '1'
|
||||
AND update_time >= %s AND update_time < %s + INTERVAL 1 DAY
|
||||
GROUP BY batch, h
|
||||
ORDER BY h
|
||||
""",
|
||||
(today, today),
|
||||
)
|
||||
|
||||
hours = [f"{h:02d}:00" for h in range(24)]
|
||||
total_by_hour = [0] * 24
|
||||
by_batch = {}
|
||||
|
||||
for batch, h, cnt in cur.fetchall():
|
||||
if h is None:
|
||||
continue
|
||||
h = int(h)
|
||||
by_batch.setdefault(batch, [0] * 24)[h] += int(cnt)
|
||||
total_by_hour[h] += int(cnt)
|
||||
|
||||
# 今日累计完成总数
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*) FROM drug_detail_list
|
||||
WHERE is_ok = '1'
|
||||
AND update_time >= %s AND update_time < %s + INTERVAL 1 DAY
|
||||
""",
|
||||
(today, today),
|
||||
)
|
||||
today_done = int(cur.fetchone()[0] or 0)
|
||||
|
||||
# 今日峰值时段(用于前端文案)
|
||||
peak_hour = None
|
||||
if today_done > 0:
|
||||
peak_idx = max(range(24), key=lambda i: total_by_hour[i])
|
||||
peak_hour = {"hour": hours[peak_idx], "count": total_by_hour[peak_idx]}
|
||||
|
||||
return {
|
||||
"date": today,
|
||||
"hours": hours,
|
||||
"total_by_hour": total_by_hour,
|
||||
"by_batch": by_batch,
|
||||
"today_done": today_done,
|
||||
"peak": peak_hour,
|
||||
}
|
||||
|
||||
|
||||
def build_payload():
|
||||
"""查库并组装完整统计结果。"""
|
||||
with get_conn() as conn:
|
||||
cur = conn.cursor()
|
||||
batches = fetch_batch_stats(cur)
|
||||
hourly = fetch_hourly_stats(cur)
|
||||
cur.execute("SELECT COUNT(*) FROM drug_detail_list")
|
||||
grand_total = int(cur.fetchone()[0] or 0)
|
||||
cur.close()
|
||||
|
||||
total = sum(b["total"] for b in batches)
|
||||
done = sum(b["done"] for b in batches)
|
||||
return {
|
||||
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"batches": batches,
|
||||
"hourly": hourly,
|
||||
"summary": {
|
||||
"grand_total": grand_total, # 全表行数(含 is_ok=99、batch 为空的行,仅作参考)
|
||||
"total": total, # 有效统计任务总量(排除 99)
|
||||
"done": done,
|
||||
"undone": total - done,
|
||||
"rate": round(done / total * 100, 1) if total else 0.0,
|
||||
"batch_count": len(batches),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_stats(force: bool = False):
|
||||
"""
|
||||
带缓存地取统计结果。
|
||||
force=True 时忽略缓存立即重算(手动刷新)。
|
||||
"""
|
||||
now = time.time()
|
||||
with _lock:
|
||||
cached = _cache["data"]
|
||||
fresh = cached is not None and (now - _cache["ts"]) < CACHE_TTL
|
||||
|
||||
if fresh and not force:
|
||||
payload = dict(cached)
|
||||
payload["cached"] = True
|
||||
payload["cache_age"] = int(now - _cache["ts"])
|
||||
return payload
|
||||
|
||||
# 缓存未命中或在锁外执行慢查询,避免阻塞其他请求
|
||||
payload = build_payload()
|
||||
|
||||
with _lock:
|
||||
_cache["data"] = payload
|
||||
_cache["ts"] = time.time()
|
||||
|
||||
result = dict(payload)
|
||||
result["cached"] = False
|
||||
result["cache_age"] = 0
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 路由
|
||||
@app.get("/api/stats")
|
||||
def api_stats(force: int = Query(0, description="传 1 强制刷新,跳过 30 分钟缓存")):
|
||||
"""看板统计数据接口。"""
|
||||
try:
|
||||
data = get_stats(force=bool(force))
|
||||
except pymysql.MySQLError as e:
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={"error": "数据库查询失败", "detail": str(e)},
|
||||
)
|
||||
resp = JSONResponse(content=data)
|
||||
resp.headers["Cache-Control"] = "no-store"
|
||||
return resp
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def api_health():
|
||||
"""健康检查:探测数据库连通性。"""
|
||||
try:
|
||||
with get_conn() as conn:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
cur.close()
|
||||
return {"status": "ok", "db": "connected"}
|
||||
except pymysql.MySQLError as e:
|
||||
return JSONResponse(status_code=503, content={"status": "error", "detail": str(e)})
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index():
|
||||
return FileResponse(STATIC_DIR / "index.html")
|
||||
|
||||
|
||||
if STATIC_DIR.exists():
|
||||
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host="127.0.0.1", port=7788)
|
||||
Reference in New Issue
Block a user