Files
pricing_review/build_portable.py
lianjianwei2024 eea5d511dc fix(build): 打包冒烟改为门禁感知断言并补充授权手册
- 冒烟①不再直探 /api/admin/summary(未激活回 403 会构建失败),改为校验 /api/license/status 的 enforce=true,并按 can_run 断言业务 API 403/200
- 设置弹框重开时激活表单复位收起;common.js 版本号递增至 20261010b
- 使用手册新增第 13 章《软件授权》(激活/续费/换机/提示语对照)
- 调整 release/testdata/run_cfg.json 测试数据参数
2026-10-10 18:15:33 +08:00

247 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""构建单机便携版(方案 B:embeddable Python + bat,2026-10-07 主人定)。
与旧 PyInstaller 路线的区别:
· 主执行文件 = python.org 官方签名的 python.exe(embeddable 包)→ 杀软误报率大幅降低;
· 升级 = 替换 造价审核\app 目录,运行时不用重发;
· 空库分发:测试数据不再出门,目标机首次运行自动建表。
用法(在开发机上,需可访问 python.org;有本地缓存则离线可用):
python build_portable.py # 构建 + 冒烟(服务 200 + 隐藏窗口初始化)
产物:release/PricingReview-Windows-x64/(目录,可直接拷贝)与同名 .zip。
"""
import io
import json
import os
import pathlib
import shutil
import subprocess
import sys
import urllib.request
import zipfile
ROOT = pathlib.Path(__file__).resolve().parent
NAME = "PricingReview-Windows-x64"
OUT = ROOT / "release"
PACKAGE = OUT / NAME
APP = ROOT / "造价审核" / "app"
# 与开发环境同大版本的 embeddable 包(多备几个补丁号,第一个能下载的胜出)
EMBED_VERSIONS = ["3.13.9", "3.13.11", "3.13.12", "3.13.14", "3.13.5", "3.13.2"]
DEPS = ["pywebview==6.2.1", "openpyxl==3.1.5", "xlrd==2.0.1"]
BAT_GUI = (
"@echo off\r\n"
"cd /d \"%~dp0\"\r\n"
"echo 正在启动造价审核窗口,请稍候...\r\n"
"\"%~dp0python\\python.exe\" \"%~dp0launch.py\"\r\n"
"if errorlevel 1 pause\r\n"
)
BAT_ADMIN = (
"@echo off\r\n"
"cd /d \"%~dp0\"\r\n"
"echo 正在启动后台服务,请稍候...\r\n"
"\"%~dp0python\\python.exe\" \"%~dp0launch.py\" admin\r\n"
"echo.\r\n"
"echo 关闭这个黑窗口 = 停止服务。\r\n"
"pause\r\n"
)
README = r"""造价审核 · 单机便携版
========================
启动
· 双击「启动造价审核.bat」:弹出软件窗口(审核工作台);
· 双击「启动后台管理.bat」:用浏览器打开后台管理(关闭黑窗口 = 停止服务)。
要求
· Windows 10/11 64 位;
· 独立窗口需要 Microsoft Edge WebView2 运行库(多数系统自带;缺失时软件会提示并
引导安装,也可直接用浏览器模式)。下载页:
https://developer.microsoft.com/microsoft-edge/webview2/
· 不需要安装 Python 或任何其他组件。
数据
· 全部数据存在「造价审核\data」文件夹里(数据库 + 上传的文件)。
· 拷贝/搬家:关掉软件后把整个文件夹一起拷走。
· 本包为空库:首次启动自动建表,从零开始录入。
排错
· 窗口/页面起不来时,用终端运行 bat 看报错;把 造价审核\data\launch.log 一并带给维护人。
"""
def log(msg):
print(msg, flush=True)
def fetch_embeddable(cache_dir):
"""取 embeddable zip:先看本地缓存,没有就按候选版本从 python.org 下载。"""
cache_dir.mkdir(parents=True, exist_ok=True)
for ver in EMBED_VERSIONS:
cached = cache_dir / ("python-%s-embed-amd64.zip" % ver)
if cached.is_file() and cached.stat().st_size > 1_000_000:
log("使用缓存 %s" % cached.name)
return cached
url = "https://www.python.org/ftp/python/%s/python-%s-embed-amd64.zip" % (ver, ver)
try:
log("下载 %s …" % url)
req = urllib.request.Request(url, headers={"User-Agent": "pricing-review-build"})
with urllib.request.urlopen(req, timeout=60) as r, open(cached, "wb") as f:
f.write(r.read())
if cached.stat().st_size > 1_000_000:
return cached
except Exception as e:
log(" 失败:%s" % e)
if cached.exists():
cached.unlink()
raise RuntimeError(
"embeddable 包取不到:请手动下载 python-3.13.x-embed-amd64.zip 放到 %s" % cache_dir)
def write_gbk(path, text):
"""bat 红线:GBK + CRLF;中文路径一律经 %~dp0 / 英文名脚本,不写死在 bat 里。"""
with open(path, "w", encoding="gbk", newline="") as f:
f.write(text)
# ---- 交付版授权信任根(决策 31,P0-1 烧根)----
# 生产公钥维护在 app/server/license_client/pinned_keys.json(运维交付后追加),
# 构建时把公钥/平台地址/强制开关烧进包内 license_build_config.py —— 客户侧改
# pinned_keys.json / data\license\config.json / 环境变量都不再影响交付版门禁。
RELEASE_API_BASE = "https://license.yihuiyong.cn"
RELEASE_PRODUCT_ID = None # 上线后填平台分配的产品 ID(int),None=不校验产品线
def write_license_build_config(app_target):
lic_pkg = app_target / "server" / "license_client"
pinned_file = lic_pkg / "pinned_keys.json"
keys = []
if pinned_file.is_file():
try:
keys = json.loads(pinned_file.read_text(encoding="utf-8")).get("pinned_keys") or []
except Exception as e:
raise RuntimeError("pinned_keys.json 解析失败:%s" % e)
if not keys:
log("⚠⚠⚠ pinned_keys.json 为空:这个包交付出去客户将无法激活(fail closed)!")
log("⚠⚠⚠ 上线前必须把运维交付的生产公钥填进 app/server/license_client/pinned_keys.json 再构建。")
conf = lic_pkg / "license_build_config.py"
conf.write_text(
"# 自动生成于构建期(build_portable.py)——交付版信任根,客户侧不可改、不可覆盖。\n"
"# 本文件存在时,license 门禁只信这里:data/license/config.json、LICENSE_API_BASE_URL、\n"
"# pinned_keys.json 在交付环境一律不参与(防自建信任根绕过授权)。\n"
"API_BASE = %r\n"
"ENFORCE = True\n"
"PRODUCT_ID = %r\n"
"SELFHEAL_SECONDS = 300\n"
"PINNED_KEYS = %s\n" % (RELEASE_API_BASE, RELEASE_PRODUCT_ID,
json.dumps(keys, ensure_ascii=False, indent=4)),
encoding="utf-8")
log("授权信任根已烧入 → server/license_client/license_build_config.py(公钥 %d 把)" % len(keys))
def main():
if os.name != "nt":
raise RuntimeError("请在 Windows x64 上构建")
build_py = pathlib.Path(sys.executable)
OUT.mkdir(exist_ok=True)
if PACKAGE.exists():
log("清理旧包 %s" % PACKAGE)
shutil.rmtree(PACKAGE)
PACKAGE.mkdir(parents=True)
# 1) embeddable 运行时 → python/,启用 site-packages
z = fetch_embeddable(OUT / "_cache")
py_dir = PACKAGE / "python"
log("解压运行时 → python/")
with zipfile.ZipFile(z) as zf:
zf.extractall(py_dir)
pth = py_dir / "python313._pth"
if pth.is_file():
io.open(pth, "w", encoding="ascii", newline="\n").write(
"python313.zip\n.\nLib\\site-packages\n")
else:
raise RuntimeError("解包结果里没有 python313._pth,embeddable 版本变了?")
# 2) 依赖装进包内 site-packages(用构建机的 pip 解析版本,与开发环境一致)
sp = py_dir / "Lib" / "site-packages"
log("安装依赖 → python/Lib/site-packages")
subprocess.run([str(build_py), "-m", "pip", "install", "--target", str(sp),
"--upgrade", "--no-warn-script-location"] + DEPS, check=True)
# 3) 应用代码 + 空数据目录 + 启动器
app_target = PACKAGE / "造价审核" / "app"
shutil.copytree(APP, app_target,
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"), dirs_exist_ok=True)
write_license_build_config(app_target)
data = PACKAGE / "造价审核" / "data"
for folder in ("", "uploads", "attachments", "inquiry"):
(data / folder).mkdir(parents=True, exist_ok=True)
shutil.copy2(ROOT / "launch.py", PACKAGE / "launch.py")
write_gbk(PACKAGE / "启动造价审核.bat", BAT_GUI)
write_gbk(PACKAGE / "启动后台管理.bat", BAT_ADMIN)
(PACKAGE / "使用说明.txt").write_text(README, encoding="utf-8-sig")
# 4) 冒烟:① 空库起服务 → 页面 200 → 门禁行为正确;② 隐藏窗口初始化(验 WebView2/pythonnet)
env = dict(os.environ, PR_PORT="8399")
log("冒烟①:空库起服务(PR_PORT=8399)…")
smoke = subprocess.run(
[str(py_dir / "python.exe"), "-c",
"import os,sys,time,urllib.request,urllib.error,json\n"
"sys.path.insert(0,'server'); sys.path.insert(0,'core'); sys.path.insert(0,'.')\n"
"import api_server\n"
"import threading; threading.Thread(target=api_server.run, daemon=True).start()\n"
"ok=False\n"
"for _ in range(40):\n"
" try:\n"
" r=urllib.request.urlopen('http://127.0.0.1:8399/admin.html',timeout=1)\n"
" if r.status==200: ok=True; break\n"
" except Exception: time.sleep(0.25)\n"
"assert ok, 'admin.html 不返回 200'\n"
"# 授权门禁冒烟(决策 31):交付包必须强制校验;未激活时业务 API 必须被拦 403。\n"
"# ⚠️ 不能再直接探 /api/admin/summary——未激活包它回 403,urlopen 抛 HTTPError 会让构建失败。\n"
"d=json.loads(urllib.request.urlopen('http://127.0.0.1:8399/api/license/status',timeout=5).read())['data']\n"
"assert d.get('enforce') is True, '交付包必须 enforce=true(烧根失效?)'\n"
"biz=200\n"
"try:\n"
" urllib.request.urlopen('http://127.0.0.1:8399/api/admin/summary',timeout=5)\n"
"except urllib.error.HTTPError as e:\n"
" biz=e.code\n"
"locked = not d.get('can_run')\n"
"assert (biz==403) if locked else (biz==200), '门禁行为不符:can_run=%s biz=%s' % (d.get('can_run'), biz)\n"
"print('SMOKE-SERVER-OK enforce=%s locked=%s keyring=%s' % (d.get('enforce'), locked, d.get('keyring_ready')))\n"],
cwd=app_target, env=env, capture_output=True, text=True, timeout=120)
if smoke.returncode != 0 or "SMOKE-SERVER-OK" not in (smoke.stdout or ""):
raise RuntimeError("服务冒烟失败:\n%s\n%s" % (smoke.stdout, smoke.stderr))
log(smoke.stdout.strip())
log("冒烟②:隐藏窗口初始化(WebView2 / pythonnet)…")
smoke2 = subprocess.run(
[str(py_dir / "python.exe"), "-c",
"import sys, threading, time\n"
"import webview\n"
"win = webview.create_window('smoke', 'http://127.0.0.1:1/notused', hidden=True)\n"
"t = threading.Thread(target=lambda: webview.start(debug=False), daemon=True)\n"
"t.start()\n"
"time.sleep(4)\n"
"print('SMOKE-WINDOW-OK')\n"
"os._exit(0)\n"],
cwd=app_target, env=env, capture_output=True, text=True, timeout=60)
if "SMOKE-WINDOW-OK" not in (smoke2.stdout or ""):
log("⚠ 窗口冒烟未通过(目标机将走浏览器兜底):\n%s\n%s" % (smoke2.stdout, smoke2.stderr))
else:
log(smoke2.stdout.strip())
# 5) 打 zip
archive = OUT / (NAME + ".zip")
log("打包 %s …" % archive.name)
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
for f in PACKAGE.rglob("*"):
if f.is_file():
zf.write(f, pathlib.Path(NAME) / f.relative_to(PACKAGE))
safe = str(archive).encode("ascii", "backslashreplace").decode("ascii")
log("完成:%s(目录 %s)" % (safe, PACKAGE))
if __name__ == "__main__":
main()