编辑代码
数据管理
字段字典
代码管理
服务发布
编辑:export_data.py
/home/ubuntu/app/dashboard/export_data.py
# -*- coding: utf-8 -*- """导出云库全量数据(只读)。 用途:给用户一份可带走的备份 / 可迁移到自有服务器的数据包。 红线:**只 SELECT,不写不改不删**。 """ import io import json import os import sys import time os.environ.setdefault("STORAGE_BACKEND", "cloud") import cloud_db # noqa: E402 TABLES = [ "stores", "datasets", "dataset_snapshots", "users", "tasks", "perm_applications", "alert_types", "alert_rules", "inbox", "monthly_sales", "positions", "op_logs", "change_log", "platform_credentials", "dashboard_config", ] def main(outdir: str) -> None: os.makedirs(outdir, exist_ok=True) conn = cloud_db.get_conn() manifest = {"exported_at": time.strftime("%Y-%m-%d %H:%M:%S"), "endpoint": cloud_db.ENDPOINT, "resource_id": cloud_db.RESOURCE_ID, "tables": {}} total_bytes = 0 try: for t in TABLES: t0 = time.time() try: rows = conn.execute("SELECT * FROM %s" % t).fetchall() except Exception as e: # noqa: BLE001 manifest["tables"][t] = {"error": str(e)[:160], "rows": 0} print(" %-22s 跳过:%s" % (t, str(e)[:60])) continue data = [dict(r) for r in rows] path = os.path.join(outdir, t + ".json") raw = json.dumps(data, ensure_ascii=False, indent=1, default=str) io.open(path, "w", encoding="utf-8").write(raw) size = len(raw.encode("utf-8")) total_bytes += size manifest["tables"][t] = {"rows": len(data), "bytes": size, "file": t + ".json"} print(" %-22s %5d 行 %8.1f KB %4.1fs" % (t, len(data), size / 1024, time.time() - t0)) finally: try: conn.close() except Exception: pass manifest["total_bytes"] = total_bytes io.open(os.path.join(outdir, "_manifest.json"), "w", encoding="utf-8").write( json.dumps(manifest, ensure_ascii=False, indent=2)) print("\n合计 %.1f MB → %s" % (total_bytes / 1024 / 1024, outdir)) if __name__ == "__main__": main(sys.argv[1] if len(sys.argv) > 1 else "exports")
保存到服务器
取消