初版:小白超人(从线上实例导出)
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据导出:历史轨迹 CSV 直链下载。
|
||||
|
||||
流程:登录用户在分析页点导出 → POST /api/export/create(需登录)→
|
||||
返回 /export/csv/<token> 直链(免登录,1 小时有效,一次性换浏览器可继续下载)。
|
||||
前端用 detectInAppBrowser 复用「复制链接到外部浏览器」提示(微信/原生壳内无法下载)。
|
||||
|
||||
CSV 内容:最近 3 天全部车辆点位(与库内保留策略一致)。
|
||||
"""
|
||||
import csv
|
||||
import datetime as dt
|
||||
import io
|
||||
import secrets
|
||||
|
||||
from flask import Blueprint, jsonify, request, Response
|
||||
|
||||
from db import get_db
|
||||
from routes.auth import get_current_user
|
||||
|
||||
bp = Blueprint("export", __name__)
|
||||
|
||||
EXPORT_TTL_HOURS = 1
|
||||
# 与 app.HISTORY_RETENTION_DAYS 对齐(bike_history 库内保留窗口)
|
||||
HISTORY_DAYS = 30
|
||||
|
||||
_STATE_LABELS = {
|
||||
"available": "可用", "used": "使用中", "locked": "欠压",
|
||||
"reserved": "损坏", "low": "低电量",
|
||||
}
|
||||
|
||||
|
||||
def _classify(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"
|
||||
|
||||
|
||||
def _clean_expired_tokens(conn):
|
||||
conn.execute("DELETE FROM export_tokens WHERE expires_at < datetime('now', '+8 hours')")
|
||||
|
||||
|
||||
@bp.route("/api/export/create", methods=["POST"])
|
||||
def export_create():
|
||||
"""创建导出直链。body: {type: 'history_csv'}(当前仅一种)。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json(silent=True) or {}
|
||||
export_type = str(data.get("type") or "history_csv")
|
||||
if export_type != "history_csv":
|
||||
return jsonify({"rtn_code": 400, "message": "暂不支持该导出类型"})
|
||||
|
||||
token = secrets.token_urlsafe(24)
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
expires = (dt.datetime.now(tz) + dt.timedelta(hours=EXPORT_TTL_HOURS)).strftime(
|
||||
"%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
_clean_expired_tokens(conn)
|
||||
conn.execute(
|
||||
"INSERT INTO export_tokens (token, scope, expires_at) VALUES (?, ?, ?)",
|
||||
(token, export_type, expires))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"[导出] 创建直链: user={user['email']}, 有效期至 {expires}")
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"url": f"/export/csv/{token}",
|
||||
"expires_at": expires,
|
||||
"ttl_hours": EXPORT_TTL_HOURS,
|
||||
}})
|
||||
|
||||
|
||||
@bp.route("/export/csv/<token>")
|
||||
def export_download(token):
|
||||
"""直链下载(免登录):1 小时内有效,可重复下载,换浏览器也能用。"""
|
||||
token = (token or "").strip()
|
||||
if not token or len(token) > 120:
|
||||
return jsonify({"rtn_code": 400, "message": "导出链接无效"}), 400
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT token, scope, expires_at FROM export_tokens WHERE token = ?",
|
||||
(token,)).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
return jsonify({"rtn_code": 404, "message": "导出链接不存在或已失效"}), 404
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
try:
|
||||
expires = dt.datetime.strptime(row["expires_at"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"rtn_code": 400, "message": "导出链接已失效"}), 400
|
||||
if expires <= dt.datetime.now(tz):
|
||||
return jsonify({"rtn_code": 400, "message": "导出链接已过期(有效期 1 小时),请重新生成"}), 400
|
||||
|
||||
stamp = dt.datetime.now(tz).strftime("%Y%m%d-%H%M")
|
||||
filename = f"xbniu_history_{stamp}.csv"
|
||||
|
||||
def generate():
|
||||
# UTF-8 BOM:让 Excel 直接双击打开不乱码
|
||||
yield "\ufeff"
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf, lineterminator="\n")
|
||||
writer.writerow(["bike_code", "latitude", "longitude",
|
||||
"state_label", "electric", "recorded_at"])
|
||||
yield buf.getvalue()
|
||||
buf.seek(0)
|
||||
buf.truncate(0)
|
||||
|
||||
conn = get_db()
|
||||
try:
|
||||
cursor = conn.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, bike_code
|
||||
""", (f"-{HISTORY_DAYS} days",))
|
||||
while True:
|
||||
rows = cursor.fetchmany(2000)
|
||||
if not rows:
|
||||
break
|
||||
for r in rows:
|
||||
writer.writerow([
|
||||
r["bike_code"], r["latitude"], r["longitude"],
|
||||
_STATE_LABELS.get(_classify(r["state"], r["status"], r["electric"]),
|
||||
"未知"),
|
||||
r["electric"], r["recorded_at"],
|
||||
])
|
||||
yield buf.getvalue()
|
||||
buf.seek(0)
|
||||
buf.truncate(0)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
resp = Response(generate(), mimetype="text/csv; charset=utf-8")
|
||||
resp.headers["Content-Disposition"] = f"attachment; filename=\"{filename}\""
|
||||
resp.headers["Cache-Control"] = "no-store"
|
||||
return resp
|
||||
Reference in New Issue
Block a user