1) 后台线程绑定在 __main__ 里 → WSGI/`flask run` 启动时全部静默不启动 - 新增 app.bootstrap():init_db + 恢复计时器 + 补还超期单 + 订单巡检 + 数据采集 + 订阅调度 + 告警调度,threading.Lock 保证只执行一次 - @app.before_request 首次请求兜底调用(WSGI 部署也能起来), __main__ 同样调 bootstrap() 2) expired=0 且 end_time 已过的僵尸单只在启动时清一次 - 新增 timer.sweep_overdue_rentals():全局扫描超期未还的单,按 _should_auto_return 过滤后排队 _run_recovery,进程内 10 分钟节流 - 巡检线程循环每轮调用一次(放在 _user_order_checker_loop,不污染单测) - reminder 来源的单没有上游订单,就地关闭(expired=1 + returned_at), 否则用户页面横幅永远显示「用车中」 3) 顺手修的 bug - sweep 里先把 sqlite3.Row 转 dict 再关连接,避免关库后读行 - _close_local_reminder 兼容没有 returned_at 列的极简 schema - 该测试自带的连接泄漏(断言抛错时没关库)导致 teardown PermissionError 实测(真实库):启动时 3 单真订单排队补还车,44 条本地提醒单就地关闭 测试:157 pytest(新增 sweep 排队/节流/本地单关闭)+ 32 node 全绿
732 lines
27 KiB
Python
732 lines
27 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
小白超人电动车地图 - Flask 后端 (精简入口)
|
||
"""
|
||
import sys
|
||
import io
|
||
|
||
# Windows 控制台中文输出兜底。注意:必须幂等且跳过"已经被包过/非真实终端"的流,
|
||
# 否则在 pytest 捕获(stdout 被换成临时文件对象,无 .buffer 或重包装会关闭
|
||
# pytest 的捕获文件)场景下,测试进程结束时 readouterr() 会报
|
||
# "I/O operation on closed file"。
|
||
def _force_utf8_stdio():
|
||
for name in ("stdout", "stderr"):
|
||
stream = getattr(sys, name)
|
||
# 已是 TextIOWrapper 且编码已是 utf-8 → 不重复包装
|
||
if isinstance(stream, io.TextIOWrapper) and stream.encoding.lower().replace("-", "") == "utf8":
|
||
continue
|
||
buf = getattr(stream, "buffer", None)
|
||
if buf is None:
|
||
continue # pytest 的捕获对象等非二进制缓冲流,保持原样
|
||
try:
|
||
setattr(sys, name, io.TextIOWrapper(buf, encoding="utf-8", line_buffering=True))
|
||
except (ValueError, OSError):
|
||
pass # 缓冲已分离/关闭(如 pytest teardown 阶段),保持原样
|
||
|
||
|
||
_force_utf8_stdio()
|
||
|
||
import os
|
||
import json
|
||
import time
|
||
import random
|
||
import threading
|
||
import urllib3
|
||
from pathlib import Path
|
||
from flask import Flask, jsonify, request, render_template, session
|
||
|
||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||
|
||
from db import get_db, init_db, get_user_auth, get_user_display_name
|
||
from wechat import request_api
|
||
from timer import restore_active_timers, start_all_order_checkers, _active_timers
|
||
|
||
# ========== Flask 应用 ==========
|
||
app = Flask(__name__, static_folder="static")
|
||
|
||
|
||
def _load_or_create_secret_key() -> str:
|
||
"""secret_key 不再写死在源码:优先环境变量,否则随机生成一次并持久化到
|
||
secret_key.txt(已 gitignore)。key 变化只会使管理员后台 session 失效,
|
||
普通用户登录态存数据库(sessions 表),不受影响。"""
|
||
env_key = os.environ.get("XBNIU_SECRET_KEY", "").strip()
|
||
if env_key:
|
||
return env_key
|
||
key_path = Path(__file__).parent / "secret_key.txt"
|
||
try:
|
||
if key_path.exists():
|
||
old = key_path.read_text("utf-8").strip()
|
||
if old:
|
||
return old
|
||
import secrets as _secrets
|
||
new_key = _secrets.token_hex(32)
|
||
key_path.write_text(new_key, encoding="utf-8")
|
||
return new_key
|
||
except Exception as e:
|
||
print(f"[secret_key] 读写失败,本次使用临时随机 key: {e}")
|
||
import secrets as _secrets
|
||
return _secrets.token_hex(32)
|
||
|
||
|
||
app.secret_key = _load_or_create_secret_key()
|
||
# 管理后台 cookie 仅经 HTTPS 传输(对外由 nginx 提供 TLS);
|
||
# 注意:若直接用 http:// 访问本服务,管理员登录 session 将不生效
|
||
app.config["SESSION_COOKIE_SECURE"] = True
|
||
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
||
|
||
# 注册蓝图
|
||
from routes.auth import bp as auth_bp, _client_ip, get_current_user
|
||
from routes.map_api import bp as map_bp
|
||
from routes.rental import bp as rental_bp
|
||
from routes.admin import bp as admin_bp
|
||
from routes.share import bp as share_bp
|
||
from routes.download import bp as download_bp
|
||
from routes.export import bp as export_bp
|
||
from routes.subscribe import bp as subscribe_bp
|
||
from rate_limit import hit as rl_hit
|
||
app.register_blueprint(auth_bp)
|
||
app.register_blueprint(map_bp)
|
||
app.register_blueprint(rental_bp)
|
||
app.register_blueprint(admin_bp)
|
||
app.register_blueprint(share_bp)
|
||
app.register_blueprint(download_bp)
|
||
app.register_blueprint(export_bp)
|
||
app.register_blueprint(subscribe_bp)
|
||
|
||
|
||
# ========== 未认证数据接口限速 ==========
|
||
# 这些接口无需登录即可读取车辆数据/代理上游查询,按 IP 限速。
|
||
# 计数用 _client_ip:仅当请求来自回环(nginx 同机反代)时才信任其注入的
|
||
# X-Real-IP/X-Forwarded-For 取真实客户端 IP,直连来源一律用 remote_addr,
|
||
# 客户端无法伪造。
|
||
PUBLIC_DATA_PREFIXES = (
|
||
"/api/map", "/api/bicycle", "/api/find_bike", "/api/bike_history",
|
||
"/api/analysis/", "/api/history/",
|
||
)
|
||
|
||
# 放宽 3 倍:原 15 次/分钟 -> 45 次/分钟。
|
||
# 页面加载(地图/车辆/寻车)与分析页拉取接口较多,原先 15/min 极易触发 429。
|
||
PUBLIC_DATA_MAX_PER_MIN = 45
|
||
|
||
# 已登录用户查询车辆的接口:完全豁免限速(用户建议:开锁用车、查询车辆不限速)。
|
||
# 开锁/用车/还车(/api/order/*、/api/rental/*)本就不在 PUBLIC_DATA_PREFIXES 内,
|
||
# 从未被本限流覆盖,此处一并列出以固化意图。
|
||
LOGGED_IN_EXEMPT_PREFIXES = (
|
||
"/api/map", "/api/bicycle", "/api/find_bike", "/api/bike_history",
|
||
)
|
||
|
||
|
||
@app.before_request
|
||
def _public_data_rate_limit():
|
||
path = request.path
|
||
if not path.startswith(PUBLIC_DATA_PREFIXES):
|
||
return None
|
||
# 已登录用户查询车辆接口豁免限速:避免正常用车时因页面/分析拉取被打 429
|
||
if path.startswith(LOGGED_IN_EXEMPT_PREFIXES) and get_current_user() is not None:
|
||
return None
|
||
ip = _client_ip()
|
||
if not rl_hit(("public_data", ip), PUBLIC_DATA_MAX_PER_MIN, 60):
|
||
return jsonify({"rtn_code": 429,
|
||
"message": "请求过于频繁,请稍后再试(每分钟最多 45 次)"}), 429
|
||
return None
|
||
|
||
|
||
# ========== 数据采集任务 ==========
|
||
_snapshot_lock = threading.Lock()
|
||
_last_snapshot = 0
|
||
_snapshot_fail_streak = 0 # 连续采集失败次数(凭据失效时会静默断采,这里打日志告警)
|
||
_collect_fail_alerted = False # 采集失败告警邮件已发标记(恢复成功后重置)
|
||
|
||
|
||
def get_adaptive_interval():
|
||
import datetime as dt
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
hour = dt.datetime.now(tz).hour
|
||
if hour >= 23 or hour < 7:
|
||
return random.randint(1800, 3600)
|
||
else:
|
||
return random.randint(300, 600)
|
||
|
||
|
||
def snapshot_bike_positions():
|
||
global _last_snapshot, _snapshot_fail_streak, _collect_fail_alerted
|
||
with _snapshot_lock:
|
||
if time.time() - _last_snapshot < 60:
|
||
return
|
||
_last_snapshot = time.time()
|
||
print(f"[数据采集] 开始采集电动车位置... (间隔: {get_adaptive_interval()}s)")
|
||
result = request_api("GET", "/project/map", params={"type": "3"})
|
||
saved_count = 0
|
||
if result.get("rtn_code") == 0 and result.get("data"):
|
||
if _snapshot_fail_streak >= 3:
|
||
print(f"[数据采集] 采集恢复成功(此前连续失败 {_snapshot_fail_streak} 次)")
|
||
_snapshot_fail_streak = 0
|
||
_collect_fail_alerted = False
|
||
bikes = result["data"].get("bicycleStation", [])
|
||
if bikes:
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
for bike in bikes:
|
||
try:
|
||
cursor.execute("""
|
||
INSERT INTO bike_history
|
||
(bike_code, latitude, longitude, status, state, electric, recorded_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, datetime('now', '+8 hours'))
|
||
""", (
|
||
bike.get("code", ""), float(bike.get("latitude", 0)),
|
||
float(bike.get("longitude", 0)), bike.get("status", 1),
|
||
bike.get("state", 1),
|
||
float(bike.get("electric_quantity") or bike.get("electricQuantity") or 100),
|
||
))
|
||
saved_count += 1
|
||
except Exception as ex:
|
||
print(f"[数据采集] 插入失败: {ex}")
|
||
conn.commit()
|
||
conn.close()
|
||
else:
|
||
_snapshot_fail_streak += 1
|
||
if _snapshot_fail_streak >= 3:
|
||
print(f"[数据采集] 警告: 已连续 {_snapshot_fail_streak} 次采集失败,"
|
||
f"请检查全局凭据是否失效。最近错误: {result.get('message') or result.get('error')}")
|
||
# 告警:给管理端配置的告警邮箱发一封(每次失败周期只发一次)
|
||
if not _collect_fail_alerted:
|
||
try:
|
||
import alerts
|
||
if alerts.notify_collect_failure(_snapshot_fail_streak,
|
||
result.get("message") or result.get("error")):
|
||
_collect_fail_alerted = True
|
||
except Exception as alert_exc:
|
||
print(f"[数据采集] 告警邮件发送失败: {alert_exc}")
|
||
print(f"[数据采集] 完成,采集了 {saved_count} 辆电动车")
|
||
|
||
|
||
# ========== 数据保留窗口(全库统一:bike_history 保留天数) ==========
|
||
# 与 cleanup_old_data(days=HISTORY_RETENTION_DAYS)、export.HISTORY_DAYS、
|
||
# 前端轨迹天数选择器对齐。改这里即可全库生效。
|
||
HISTORY_RETENTION_DAYS = 30
|
||
|
||
|
||
def cleanup_old_data(days=HISTORY_RETENTION_DAYS):
|
||
from pathlib import Path as P
|
||
DB_PATH = P(__file__).parent / "users.db"
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT COUNT(*) FROM bike_history WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',))
|
||
bike_old = cursor.fetchone()[0]
|
||
cursor.execute("SELECT COUNT(*) FROM sessions WHERE expires_at < datetime('now', '+8 hours')")
|
||
session_old = cursor.fetchone()[0]
|
||
total_to_delete = bike_old + session_old
|
||
if total_to_delete == 0:
|
||
conn.close()
|
||
return {"freed_mb": 0}
|
||
db_size_before = os.path.getsize(str(DB_PATH))
|
||
cursor.execute("DELETE FROM bike_history WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',))
|
||
cursor.execute("DELETE FROM sessions WHERE expires_at < datetime('now', '+8 hours')")
|
||
conn.commit()
|
||
conn.close()
|
||
try:
|
||
vconn = get_db()
|
||
vconn.execute("VACUUM")
|
||
vconn.close()
|
||
except Exception:
|
||
pass
|
||
db_size_after = os.path.getsize(str(DB_PATH))
|
||
freed_mb = (db_size_before - db_size_after) / 1024 / 1024
|
||
print(f"[数据清理] 完成: bike_history={bike_old}, sessions={session_old}, 释放 {freed_mb:.2f} MB")
|
||
return {"freed_mb": round(freed_mb, 2)}
|
||
|
||
|
||
def start_snapshot_scheduler():
|
||
last_cleanup = [0]
|
||
def run():
|
||
while True:
|
||
interval = get_adaptive_interval()
|
||
time.sleep(interval)
|
||
snapshot_bike_positions()
|
||
now = time.time()
|
||
if now - last_cleanup[0] >= 23 * 3600:
|
||
last_cleanup[0] = now
|
||
try:
|
||
cleanup_old_data(days=HISTORY_RETENTION_DAYS)
|
||
except Exception as e:
|
||
print(f"[数据清理] 失败: {e}")
|
||
t = threading.Thread(target=run, daemon=True)
|
||
t.start()
|
||
print("[数据采集] 车辆位置快照采集已启动")
|
||
|
||
|
||
# ========== 数据分析 API ==========
|
||
|
||
@app.route("/api/collect_now", methods=["POST"])
|
||
def api_collect_now():
|
||
from routes.auth import get_current_user
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
snapshot_bike_positions()
|
||
return jsonify({"rtn_code": 0, "message": "采集完成"})
|
||
|
||
|
||
@app.route("/api/bike_history")
|
||
def api_bike_history():
|
||
code = request.args.get("code", "")
|
||
if not code:
|
||
return jsonify({"rtn_code": 400, "message": "缺少 code"})
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT latitude, longitude, status, state, electric, recorded_at
|
||
FROM bike_history WHERE bike_code = ? ORDER BY recorded_at DESC LIMIT 500
|
||
""", (code,))
|
||
rows = cursor.fetchall()
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "data": [dict(r) for r in rows]})
|
||
|
||
|
||
@app.route("/api/analysis/overview")
|
||
def api_analysis_overview():
|
||
import datetime as dt
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
|
||
# 状态分布
|
||
cursor.execute("""
|
||
SELECT
|
||
CASE
|
||
WHEN state = 10 OR electric < 20 THEN 'low'
|
||
WHEN state = 4 THEN 'locked'
|
||
WHEN state = 2 THEN 'reserved'
|
||
WHEN state = 1 AND status = 1 THEN 'used'
|
||
ELSE 'available'
|
||
END as bike_state,
|
||
COUNT(DISTINCT bike_code) as count
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', '-1 hour')
|
||
GROUP BY bike_state
|
||
""")
|
||
status_dist = {row["bike_state"]: row["count"] for row in cursor.fetchall()}
|
||
|
||
# 24小时分布
|
||
cursor.execute("""
|
||
SELECT
|
||
CAST(strftime('%H', recorded_at) AS INTEGER) as hour,
|
||
CASE
|
||
WHEN state = 10 OR electric < 20 THEN 'low'
|
||
WHEN state = 4 THEN 'locked'
|
||
WHEN state = 2 THEN 'reserved'
|
||
WHEN state = 1 AND status = 1 THEN 'used'
|
||
ELSE 'available'
|
||
END as bike_state,
|
||
COUNT(DISTINCT bike_code) as cnt
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', '-24 hours')
|
||
GROUP BY hour, bike_state
|
||
""")
|
||
hourly_raw = {}
|
||
for row in cursor.fetchall():
|
||
h = row["hour"]
|
||
if h not in hourly_raw:
|
||
hourly_raw[h] = {}
|
||
hourly_raw[h][row["bike_state"]] = row["cnt"]
|
||
|
||
# 快照次数
|
||
cursor.execute("""
|
||
SELECT COUNT(DISTINCT strftime('%Y-%m-%d %H:%M', recorded_at))
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', '-24 hours')
|
||
""")
|
||
snaps = max(cursor.fetchone()[0], 1)
|
||
|
||
for h in hourly_raw:
|
||
for state in hourly_raw[h]:
|
||
hourly_raw[h][state] = round(hourly_raw[h][state] / snaps, 1)
|
||
|
||
# 活跃车辆Top10
|
||
cursor.execute("""
|
||
SELECT bike_code, COUNT(*) as cnt
|
||
FROM bike_history
|
||
WHERE state = 1 AND status = 1
|
||
AND recorded_at >= datetime('now', '+8 hours', '-24 hours')
|
||
GROUP BY bike_code ORDER BY cnt DESC LIMIT 10
|
||
""")
|
||
top_inuse = [dict(r) for r in cursor.fetchall()]
|
||
|
||
conn.close()
|
||
|
||
return jsonify({
|
||
"rtn_code": 0,
|
||
"data": {
|
||
"status_distribution": status_dist,
|
||
"hourly_distribution": hourly_raw,
|
||
"top_inuse_bikes": top_inuse,
|
||
"snapshot_count": snaps,
|
||
}
|
||
})
|
||
|
||
|
||
@app.route("/api/analysis/heatmap")
|
||
def api_analysis_heatmap():
|
||
code = request.args.get("code", "")
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
if code:
|
||
cursor.execute("""
|
||
SELECT latitude, longitude, electric, recorded_at
|
||
FROM bike_history WHERE bike_code = ? ORDER BY recorded_at ASC LIMIT 1000
|
||
""", (code,))
|
||
else:
|
||
cursor.execute("""
|
||
SELECT latitude, longitude, electric, recorded_at
|
||
FROM bike_history ORDER BY recorded_at DESC LIMIT 2000
|
||
""")
|
||
rows = cursor.fetchall()
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "data": [dict(r) for r in rows]})
|
||
|
||
|
||
# ========== 历史数据分析 API(analysis.html 前端契约) ==========
|
||
# 说明:analysis.html 调用 /api/history/* 系列接口,但这些路由此前从未实现,导致
|
||
# 数据分析页/批量车辆轨迹全部 404。以下实现与前端 analysis.html 期望的 JSON 结构对齐。
|
||
|
||
# 状态分类(与 map.html / analysis.html 图例一致)
|
||
_HISTORY_STATES = ["available", "used", "locked", "reserved", "low"]
|
||
|
||
|
||
def _classify_bike_state(state, status, electric):
|
||
try:
|
||
state = int(state)
|
||
except (TypeError, ValueError):
|
||
state = 1
|
||
try:
|
||
status = int(status)
|
||
except (TypeError, ValueError):
|
||
status = 1
|
||
try:
|
||
electric = float(electric)
|
||
except (TypeError, ValueError):
|
||
electric = 100.0
|
||
if state == 10 or electric < 20:
|
||
return "low"
|
||
if state == 4:
|
||
return "locked"
|
||
if state == 2:
|
||
return "reserved"
|
||
if state == 1 and status == 1:
|
||
return "used"
|
||
return "available"
|
||
|
||
|
||
@app.route("/api/history/stats")
|
||
def api_history_stats():
|
||
"""统计概览。days 控制时段分布窗口(1..HISTORY_RETENTION_DAYS,默认 1 天)。
|
||
|
||
days<=1 时按小时分桶(24 桶);>1 天时按天分桶(days 桶),
|
||
前端图用同一个 hourly_distribution 结构渲染,只是桶的 key 含义变为「第 N 天前」。
|
||
"""
|
||
try:
|
||
days = max(1, min(HISTORY_RETENTION_DAYS, int(request.args.get("days", 1))))
|
||
except (TypeError, ValueError):
|
||
days = 1
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
|
||
# 全量统计
|
||
cursor.execute("SELECT COUNT(DISTINCT bike_code) FROM bike_history")
|
||
bike_count = cursor.fetchone()[0] or 0
|
||
cursor.execute("SELECT COUNT(*), MIN(recorded_at), MAX(recorded_at) FROM bike_history")
|
||
row = cursor.fetchone()
|
||
total_points = row[0] or 0
|
||
earliest, latest = row[1], row[2]
|
||
|
||
# 状态分布:最近 1 小时内每辆车的最新一条记录
|
||
status_dist = {s: 0 for s in _HISTORY_STATES}
|
||
cursor.execute("""
|
||
SELECT h.bike_code, h.state, h.status, h.electric
|
||
FROM bike_history h
|
||
JOIN (
|
||
SELECT bike_code, MAX(recorded_at) AS m
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', '-1 hour')
|
||
GROUP BY bike_code
|
||
) x ON h.bike_code = x.bike_code AND h.recorded_at = x.m
|
||
""")
|
||
for r in cursor.fetchall():
|
||
status_dist[_classify_bike_state(r["state"], r["status"], r["electric"])] += 1
|
||
|
||
# 时段分布:每桶内处于各状态的不同车辆数(去重)
|
||
# days=1 → 按小时 24 桶;days>1 → 按天 days 桶(桶 key = 距今天数)
|
||
if days <= 1:
|
||
cursor.execute("""
|
||
SELECT strftime('%H', recorded_at) AS h, bike_code, state, status, electric
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', '-24 hours')
|
||
""")
|
||
rows = cursor.fetchall()
|
||
bucket_key_fn = lambda r: int(r["h"]) # noqa: E731
|
||
bucket_count = 24
|
||
bucket_label = lambda i: "%02d" % i # noqa: E731
|
||
else:
|
||
cursor.execute("""
|
||
SELECT CAST(julianday(datetime('now', '+8 hours')) -
|
||
julianday(recorded_at) AS INTEGER) AS d,
|
||
bike_code, state, status, electric
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', ?)
|
||
""", (f"-{days} days",))
|
||
rows = cursor.fetchall()
|
||
# 桶序 = 距今天数:0=今天、1=昨天、…、days-1=最老(与前端"今天/昨天/N天前"一致)
|
||
bucket_key_fn = lambda r: min(days - 1, max(0, int(r["d"] or 0))) # noqa: E731
|
||
bucket_count = days
|
||
bucket_label = lambda i: str(i) # noqa: E731
|
||
|
||
seen = set()
|
||
hourly_raw = {}
|
||
for r in rows:
|
||
key = (r["bike_code"], bucket_key_fn(r),
|
||
_classify_bike_state(r["state"], r["status"], r["electric"]))
|
||
if key in seen:
|
||
continue
|
||
seen.add(key)
|
||
st = key[2]
|
||
hour_bucket = hourly_raw.setdefault(key[1], {})
|
||
hour_bucket[st] = hour_bucket.get(st, 0) + 1
|
||
|
||
hourly_distribution = {}
|
||
for i in range(bucket_count):
|
||
d = hourly_raw.get(i, {})
|
||
hourly_distribution[bucket_label(i)] = {s: d.get(s, 0) for s in _HISTORY_STATES}
|
||
|
||
# 每桶平均(供统计卡片展示)
|
||
hourly_avg = {}
|
||
for s in _HISTORY_STATES:
|
||
vals = [hourly_distribution[bucket_label(i)][s] for i in range(bucket_count)]
|
||
hourly_avg[s] = round(sum(vals) / float(bucket_count), 1)
|
||
|
||
# 活跃车辆 Top10:窗口内处于“使用中”的次数
|
||
cursor.execute("""
|
||
SELECT bike_code, COUNT(*) AS cnt
|
||
FROM bike_history
|
||
WHERE state = 1 AND status = 1
|
||
AND recorded_at >= datetime('now', '+8 hours', ?)
|
||
GROUP BY bike_code
|
||
ORDER BY cnt DESC
|
||
LIMIT 10
|
||
""", (f"-{days} days",))
|
||
top_bikes = [{"bike_code": r["bike_code"], "point_count": r["cnt"]} for r in cursor.fetchall()]
|
||
|
||
conn.close()
|
||
return jsonify({
|
||
"rtn_code": 0,
|
||
"data": {
|
||
"days": days,
|
||
"total": {"bike_count": bike_count, "total_points": total_points,
|
||
"earliest": earliest, "latest": latest},
|
||
"status_distribution": status_dist,
|
||
"hourly_distribution": hourly_distribution,
|
||
"hourly_avg": hourly_avg,
|
||
"top_bikes": top_bikes,
|
||
}
|
||
})
|
||
|
||
|
||
@app.route("/api/history/bikes")
|
||
def api_history_bikes():
|
||
"""列出保留窗口内有历史点的车。"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT bike_code, COUNT(*) AS point_count
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', ?)
|
||
GROUP BY bike_code
|
||
ORDER BY point_count DESC
|
||
LIMIT 800
|
||
""", (f"-{HISTORY_RETENTION_DAYS} days",))
|
||
rows = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"days": HISTORY_RETENTION_DAYS, "bikes": rows}})
|
||
|
||
|
||
@app.route("/api/history/trajectory")
|
||
def api_history_trajectory():
|
||
"""单辆车轨迹回放:points 数组,字段与 analysis.html 单车模式读取一致。"""
|
||
bike_code = (request.args.get("bike_code") or "").strip()
|
||
# 轨迹窗口与库内保留策略一致
|
||
try:
|
||
days = max(1, min(HISTORY_RETENTION_DAYS, int(request.args.get("days", 3))))
|
||
except (TypeError, ValueError):
|
||
days = 3
|
||
if not bike_code:
|
||
return jsonify({"rtn_code": 400, "message": "缺少 bike_code"})
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT latitude, longitude, state, status, electric, recorded_at
|
||
FROM bike_history
|
||
WHERE bike_code = ? AND recorded_at >= datetime('now', '+8 hours', ?)
|
||
ORDER BY recorded_at ASC
|
||
LIMIT 3000
|
||
""", (bike_code, f"-{days} days"))
|
||
points = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
# truncated=true 表示窗口内点位超过 LIMIT 被截断(前端提示)
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"bike_code": bike_code, "days": days,
|
||
"truncated": len(points) >= 3000, "points": points}})
|
||
|
||
|
||
@app.route("/api/history/all_trajectory")
|
||
def api_history_all_trajectory():
|
||
"""多车(全部车辆)轨迹:trajectories 为 {bike_code: [ {lat,lng,time,state,status,electric}, ... ]}。"""
|
||
try:
|
||
days = max(1, min(HISTORY_RETENTION_DAYS, int(request.args.get("days", 1))))
|
||
except (TypeError, ValueError):
|
||
days = 1
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT bike_code, latitude, longitude, state, status, electric, recorded_at
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', ?)
|
||
ORDER BY recorded_at ASC
|
||
LIMIT 200000
|
||
""", (f"-{days} days",))
|
||
trajectories = {}
|
||
fetched = 0
|
||
for r in cursor.fetchall():
|
||
fetched += 1
|
||
code = r["bike_code"]
|
||
trajectories.setdefault(code, []).append({
|
||
"lat": r["latitude"], "lng": r["longitude"],
|
||
"time": r["recorded_at"], "state": r["state"],
|
||
"status": r["status"], "electric": r["electric"],
|
||
})
|
||
conn.close()
|
||
# 截断提示:行数达到 LIMIT 说明大概率还有更多数据没取出来
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"days": days, "truncated": fetched >= 200000,
|
||
"trajectories": trajectories}})
|
||
|
||
|
||
@app.route("/api/history/heatmap")
|
||
def api_history_heatmap():
|
||
"""热力图(服务端网格聚合):bounds / points[{lat,lng,count}] / max_count / grid_count / total_points。"""
|
||
step = 0.0012 # 约 130m 网格
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT latitude, longitude
|
||
FROM bike_history
|
||
WHERE recorded_at >= datetime('now', '+8 hours', '-48 hours')
|
||
""")
|
||
cells = {}
|
||
total_points = 0
|
||
for r in cursor.fetchall():
|
||
lat = r["latitude"]
|
||
lng = r["longitude"]
|
||
if lat is None or lng is None:
|
||
continue
|
||
key = (round(float(lat) / step) * step, round(float(lng) / step) * step)
|
||
cells[key] = cells.get(key, 0) + 1
|
||
total_points += 1
|
||
conn.close()
|
||
|
||
points = [{"lat": k[0], "lng": k[1], "count": v} for k, v in cells.items()]
|
||
max_count = max((p["count"] for p in points), default=1)
|
||
if points:
|
||
bounds = {
|
||
"min_lat": min(p["lat"] for p in points),
|
||
"max_lat": max(p["lat"] for p in points),
|
||
"min_lng": min(p["lng"] for p in points),
|
||
"max_lng": max(p["lng"] for p in points),
|
||
}
|
||
else:
|
||
bounds = None
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"bounds": bounds, "points": points,
|
||
"max_count": max_count, "grid_count": len(points),
|
||
"total_points": total_points,
|
||
}})
|
||
|
||
|
||
# ========== 启动 ==========
|
||
# 后台线程原来只挂在 `if __name__ == "__main__":` 里,换成 gunicorn/`flask run`
|
||
# 或任何 WSGI 启动方式时全都不会启动(且静默)——定时采集、订单巡检、
|
||
# 自动还车、订阅提醒、凭据告警会一起残废。这里收进幂等的 bootstrap(),
|
||
# WSGI 与 __main__ 都会调用,再由 before_request 兜住「首次请求」。
|
||
_bootstrap_lock = threading.Lock()
|
||
_bootstrap_done = False
|
||
|
||
|
||
def bootstrap():
|
||
"""初始化数据库并启动所有后台线程。幂等:重复调用只会执行一次。"""
|
||
global _bootstrap_done
|
||
with _bootstrap_lock:
|
||
if _bootstrap_done:
|
||
return False
|
||
_bootstrap_done = True
|
||
|
||
print("[启动] bootstrap: 初始化数据库 + 启动后台线程")
|
||
try:
|
||
init_db()
|
||
except Exception as exc:
|
||
print(f"[启动] init_db 失败: {exc}")
|
||
|
||
steps = [
|
||
("恢复计时器", restore_active_timers),
|
||
("补还超期订单", _sweep_on_boot),
|
||
("订单巡检", start_all_order_checkers),
|
||
("数据采集", start_snapshot_scheduler),
|
||
]
|
||
for name, fn in steps:
|
||
try:
|
||
fn()
|
||
except Exception as exc:
|
||
print(f"[启动] {name} 失败: {exc}")
|
||
|
||
try:
|
||
from subscribe import start_subscribe_scheduler
|
||
start_subscribe_scheduler()
|
||
except Exception as exc:
|
||
print(f"[启动] 订阅调度失败: {exc}")
|
||
|
||
try:
|
||
from alerts import start_alert_scheduler
|
||
start_alert_scheduler()
|
||
except Exception as exc:
|
||
print(f"[启动] 告警调度失败: {exc}")
|
||
|
||
print("[启动] bootstrap 完成")
|
||
return True
|
||
|
||
|
||
def _sweep_on_boot():
|
||
"""启动时把「expired=0 且已过期」的僵尸单捞一遍(带 5 分钟节流)。"""
|
||
try:
|
||
from timer import sweep_overdue_rentals
|
||
n = sweep_overdue_rentals(force=True)
|
||
if n:
|
||
print(f"[启动] 补还超期订单 {n} 单")
|
||
except Exception as exc:
|
||
print(f"[启动] 补还超期订单失败: {exc}")
|
||
|
||
|
||
@app.before_request
|
||
def _ensure_bootstrap():
|
||
"""WSGI 部署(gunicorn 等)不会走 __main__,靠首个请求把后台线程拉起来。"""
|
||
if not _bootstrap_done:
|
||
bootstrap()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
bootstrap()
|
||
PORT = 98
|
||
# 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。
|
||
# 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。
|
||
print(f"[启动] HTTP 服务: http://127.0.0.1:{PORT} (请由 nginx 反代对外提供 HTTPS)")
|
||
app.run(host=os.environ.get("XBCR_HOST","0.0.0.0"), port=int(os.environ.get("XBCR_PORT",PORT)), debug=False)
|