localstore.py
7.74 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# -*- coding: utf-8 -*-
"""本地结果目录:每次动作一个文件夹,方便人工核对。
edge_data\\20261021\\153012_scan\\
summary.json 本次动作的结论(给程序/云端用)
*.json 接口原始返回(已脱敏)
*.csv 表格(utf-8-sig,Excel 直接打开)
*.png 截图
index.html 汇总页(双击用浏览器打开即可)
edge_data\\index.html 所有动作的目录页
"""
import csv
import datetime
import html
import json
import logging
import os
import shutil
INDEX_LIMIT = 300 # 目录页只列最近这么多次动作(目录页不再越来越慢)
log = logging.getLogger("edge")
from .logs import scrub
class RunDir(object):
def __init__(self, data_dir, action):
now = datetime.datetime.now()
self.root = data_dir
self.action = action
self.started = now.strftime("%Y-%m-%d %H:%M:%S")
self.path = os.path.join(data_dir, now.strftime("%Y%m%d"), now.strftime("%H%M%S") + "_" + action)
os.makedirs(self.path, exist_ok=True)
self.sections = [] # [(标题, html)]
self.files = []
def file(self, name):
return os.path.join(self.path, name)
def write_json(self, name, obj):
text = scrub(json.dumps(obj, ensure_ascii=False, indent=2, default=str))
with open(self.file(name), "w", encoding="utf-8") as f:
f.write(text)
self.files.append(name)
return self.file(name)
def write_csv(self, name, rows, columns=None):
columns = columns or (list(rows[0].keys()) if rows else [])
with open(self.file(name), "w", encoding="utf-8-sig", newline="") as f:
w = csv.writer(f)
w.writerow(columns)
for r in rows:
w.writerow(["" if r.get(c) is None else r.get(c) for c in columns])
self.files.append(name)
return self.file(name)
def open_csv_writer(self, name, columns):
f = open(self.file(name), "w", encoding="utf-8-sig", newline="")
w = csv.writer(f)
w.writerow(columns)
self.files.append(name)
return f, w
def table(self, title, rows, columns, labels=None, limit=500):
labels = labels or columns
h = ["<table><tr>%s</tr>" % "".join("<th>%s</th>" % html.escape(str(l)) for l in labels)]
for r in rows[:limit]:
h.append("<tr>%s</tr>" % "".join(
"<td>%s</td>" % html.escape("" if r.get(c) is None else str(r.get(c))) for c in columns))
h.append("</table>")
if len(rows) > limit:
h.append("<p class=muted>只显示前 %d 行,共 %d 行,完整数据见 CSV。</p>" % (limit, len(rows)))
self.sections.append((title, "".join(h)))
def note(self, title, text, level="info"):
self.sections.append((title, "<p class=%s>%s</p>" % (level, html.escape(text).replace("\n", "<br>"))))
def image(self, title, name):
self.sections.append((title, '<a href="%s" target=_blank><img src="%s"></a>' % (name, name)))
def finish(self, ok, summary):
summary = dict(summary or {})
summary.update({"action": self.action, "ok": bool(ok), "started": self.started,
"finished": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
self.write_json("summary.json", summary)
status = "成功" if ok else "失败"
body = "".join("<h2>%s</h2>%s" % (html.escape(t), c) for t, c in self.sections)
files = "".join('<li><a href="%s">%s</a></li>' % (n, n) for n in sorted(set(self.files)))
page = PAGE % {"title": "%s · %s" % (self.action, status), "status": status,
"cls": "ok" if ok else "err", "started": self.started, "body": body, "files": files,
"msg": html.escape(summary.get("message") or "")}
with open(self.file("index.html"), "w", encoding="utf-8") as f:
f.write(page)
_rebuild_root_index(self.root)
return self.file("index.html")
def old_entries(data_dir, keep_days):
"""超过 keep_days 天的本地结果目录(edge_data/YYYYMMDD)和残留的日志包 / 诊断目录(只列出,不删)。"""
if not keep_days or not os.path.isdir(data_dir):
return []
cut = (datetime.date.today() - datetime.timedelta(days=max(1, int(keep_days)))).strftime("%Y%m%d")
out = []
for day in os.listdir(data_dir):
if day.isdigit() and len(day) == 8 and day < cut:
out.append(os.path.join(data_dir, day))
elif day.startswith(("upload_logs_", "diag_")):
stamp = "".join(ch for ch in day if ch.isdigit())[:8] # 上传失败残留的日志包 / 诊断目录
if len(stamp) == 8 and stamp < cut:
out.append(os.path.join(data_dir, day))
return out
def cleanup(data_dir, keep_days):
"""删除超过 keep_days 天的本地结果目录(edge_data/YYYYMMDD)。返回删除的天数。"""
n = 0
for p in old_entries(data_dir, keep_days):
name = os.path.basename(p)
if os.path.isdir(p):
shutil.rmtree(p, ignore_errors=True)
else:
try:
os.remove(p)
except OSError:
pass
if name.isdigit():
n += 1
if n:
log.info("已清理 %d 天前的本地结果目录 %d 个(保留 %d 天)", keep_days, n, keep_days)
_rebuild_root_index(data_dir)
return n
def _rebuild_root_index(data_dir):
items = []
for day in sorted(os.listdir(data_dir), reverse=True):
dpath = os.path.join(data_dir, day)
if not (os.path.isdir(dpath) and day.isdigit()):
continue
if len(items) >= INDEX_LIMIT:
break
for run in sorted(os.listdir(dpath), reverse=True):
if len(items) >= INDEX_LIMIT:
break
sj = os.path.join(dpath, run, "summary.json")
if not os.path.exists(sj):
continue
try:
with open(sj, encoding="utf-8") as f:
s = json.load(f)
except Exception:
continue
items.append('<tr><td>%s</td><td><a href="%s/%s/index.html">%s</a></td><td class=%s>%s</td><td>%s</td></tr>' % (
html.escape(s.get("started", "")), day, run, html.escape(s.get("action", run)),
"ok" if s.get("ok") else "err", "成功" if s.get("ok") else "失败", html.escape(s.get("message") or "")))
page = PAGE % {"title": "取数端本地结果", "status": "", "cls": "", "started": "", "files": "", "msg": "",
"body": "<table><tr><th>时间</th><th>动作</th><th>结果</th><th>说明</th></tr>%s</table>" % "".join(items)}
with open(os.path.join(data_dir, "index.html"), "w", encoding="utf-8") as f:
f.write(page)
PAGE = """<!doctype html><html><head><meta charset="utf-8"><title>%(title)s</title>
<style>
body{font-family:"Microsoft YaHei",sans-serif;margin:16px;color:#222;background:#fafafa}
h1{font-size:20px}h2{font-size:16px;margin-top:24px;border-left:4px solid #1677ff;padding-left:8px}
table{border-collapse:collapse;background:#fff;font-size:13px;margin:8px 0}
th,td{border:1px solid #ddd;padding:4px 8px;text-align:left;white-space:nowrap}th{background:#f0f4fa}
.ok{color:#18a058;font-weight:bold}.err{color:#d03050;font-weight:bold}.warn{color:#c27c0e}.muted{color:#888}
img{max-width:100%%;border:1px solid #ccc}
</style></head><body>
<h1>%(title)s</h1><p>开始时间:%(started)s <span class="%(cls)s">%(status)s</span> %(msg)s</p>
<p class=muted>本页由门店取数端自动生成,数据来自真实 DMS 接口原始返回,用于人工核对。</p>
%(body)s
<h2>文件</h2><ul>%(files)s</ul>
<p><a href="../../index.html">← 返回目录</a></p>
</body></html>"""