"""批 2 验收脚本:500 行 Excel 导入(规范 5.3 兜底通道)。 覆盖:模板下载 → 上传解析预览 → 确认异步落库 → 轮询结果 → 下载错误清单。 只读/只写本地 parking_cloud_yudao,签名与 HTTP 上报完全一致(含二进制 body 哈希)。 """ import base64 import hashlib import hmac import io import json import time import urllib.error import urllib.request import uuid import openpyxl BASE = "http://127.0.0.1:48083" ADMIN = BASE + "/admin-api" PREFIX = "/open-api/dsp/v1" PLATFORM_CODE = "CF-HS" ROWS = 500 BAD_ROWS = {100, 250, 400} # 这三行故意把泊位状态写成 9,应进错误清单 def http(method, url, body=None, headers=None): req = urllib.request.Request(url, data=body, headers=headers or {}, method=method) try: with urllib.request.urlopen(req) as resp: return resp.status, resp.read(), dict(resp.headers) except urllib.error.HTTPError as e: return e.code, e.read(), dict(e.headers) def admin_call(method, path, token=None, body=None): headers = {"Content-Type": "application/json"} if token: headers["Authorization"] = "Bearer " + token status, raw, _ = http(method, ADMIN + path, json.dumps(body).encode() if body else None, headers) payload = json.loads(raw.decode("utf-8")) if raw else {} if status != 200 or payload.get("code") != 0: raise SystemExit(f"管理端调用失败 {method} {path}: http={status} {payload.get('msg')}") return payload.get("data") def sign(secret, method, path, timestamp, nonce, body): source = "\n".join([method, path, PLATFORM_CODE, timestamp, nonce, hashlib.sha256(body).hexdigest()]) return hmac.new(base64.b64decode(secret), source.encode("utf-8"), hashlib.sha256).hexdigest() def dsp_call(secret, method, path, body=None, request_id=None): body = body or b"" ts = str(int(time.time() * 1000)) nonce = uuid.uuid4().hex headers = { "X-Platform-Code": PLATFORM_CODE, "X-Timestamp": ts, "X-Nonce": nonce, "X-Sign": sign(secret, method, path, ts, nonce, body), } if request_id: headers["X-Request-Id"] = request_id if body: headers["Content-Type"] = "application/octet-stream" return http(method, BASE + path, body, headers) def build_workbook(headers): wb = openpyxl.Workbook() ws = wb.active ws.append(headers) for i in range(1, ROWS + 1): status = 9 if i in BAD_ROWS else 1 ws.append([ "HS-PL-0001", f"GTB-{500 + i:03d}", "HS-PL-0001-A02", "钢铁街北侧 002-A02", 1, status, "北侧", "车头朝东", "平行", "118.88771", "42.257645", 1, time.strftime("%Y-%m-%d %H:%M:%S"), ]) out = io.BytesIO() wb.save(out) return out.getvalue() def main(): token = admin_call("POST", "/system/auth/login", body={"username": "admin", "password": "admin123"})["accessToken"] page = admin_call("GET", "/park/dsp-platform/page?platformCode=" + PLATFORM_CODE + "&pageSize=10", token) secret = admin_call("PUT", f"/park/dsp-platform/reset-key?id={page['list'][0]['id']}", token)["secretKey"] print("== 1. 下载模板 ==") status, raw, headers = dsp_call(secret, "GET", PREFIX + "/import/template/berth", request_id="imp-" + uuid.uuid4().hex[:12]) print(f" 模板 http={status} bytes={len(raw)} 类型={headers.get('Content-Type', '')[:60]}") assert status == 200 and len(raw) > 4000 wb = openpyxl.load_workbook(io.BytesIO(raw)) header_row = [c.value for c in wb.worksheets[0][1]] print(f" 模板表头 {len(header_row)} 列:{header_row[:5]} …") assert len(wb.worksheets) == 2, "模板应含「数据」与「填写说明」两个工作表" print("== 2. 上传 500 行(其中 3 行泊位状态非法) ==") file_bytes = build_workbook(header_row) status, raw, _ = dsp_call(secret, "POST", PREFIX + "/import/upload/berth", file_bytes, request_id="imp-" + uuid.uuid4().hex[:12]) payload = json.loads(raw.decode("utf-8")) data = payload.get("data") or {} print(f" http={status} code={payload.get('code')} totalRows={data.get('totalRows')} " f"errorCount={data.get('errorCount')} preview={len(data.get('previewRows') or [])}") assert payload.get("code") == 0 and data.get("totalRows") == ROWS, payload task_id = data["taskId"] print("== 3. 确认导入 ==") status, raw, _ = dsp_call(secret, "POST", PREFIX + f"/import/confirm/{task_id}", request_id="imp-" + uuid.uuid4().hex[:12]) payload = json.loads(raw.decode("utf-8")) print(f" http={status} code={payload.get('code')} status={payload['data']['statusText']}") print("== 4. 轮询结果 ==") final = None for _ in range(60): status, raw, _ = dsp_call(secret, "GET", PREFIX + f"/import/result/{task_id}", request_id="imp-" + uuid.uuid4().hex[:12]) final = json.loads(raw.decode("utf-8"))["data"] if final["status"] in (2, 3): break time.sleep(1) print(f" status={final['statusText']} 总数={final['totalRows']} 成功={final['successRows']} " f"失败={final['failRows']} 错误文件={final['errorFileReady']}") assert final["status"] == 2, final assert final["successRows"] == ROWS - len(BAD_ROWS), final assert final["failRows"] == len(BAD_ROWS), final print("== 5. 下载错误清单 ==") status, raw, headers = dsp_call(secret, "GET", PREFIX + f"/import/error-file/{task_id}", request_id="imp-" + uuid.uuid4().hex[:12]) print(f" http={status} bytes={len(raw)}") assert status == 200 wb = openpyxl.load_workbook(io.BytesIO(raw)) ws = wb.worksheets[0] print(f" 表头:{[c.value for c in ws[1]][:5]} … 共 {ws.max_row - 1} 行错误") for row in ws.iter_rows(min_row=2, max_row=min(5, ws.max_row), values_only=True): print(f" 行{row[0]} {row[1]} {row[2]}") print("== 6. 幂等:同一 requestId 重复上传 ==") rid = "imp-" + uuid.uuid4().hex[:12] _, raw1, _ = dsp_call(secret, "POST", PREFIX + "/import/upload/berth", file_bytes, request_id=rid) _, raw2, _ = dsp_call(secret, "POST", PREFIX + "/import/upload/berth", file_bytes, request_id=rid) print(f" 两次响应一致:{raw1 == raw2}") print("\n批 2 Excel 导入验收通过") if __name__ == "__main__": main()