# -*- coding: utf-8 -*- """起一个"隔离副本"后台服务:把 app 源码拷进系统临时目录再启动,生产库零接触。 做法与 app/tests/api_harness.py 同款(照抄口径): <临时目录>/CostReview/app ← 拷贝的源码(库路径由 __file__ 推导,自然指向副本) <临时目录>/后台需要导入的项目 ← SRC_DIR(放样例工程文件) <临时目录>/lic/config.json ← {"enforce": false}(开发豁免,业务接口全放行) 环境变量 PR_PORT=随机空闲端口,LICENSE_DATA_DIR=临时 lic 目录。 """ import os import shutil import socket import subprocess import sys import tempfile import time import httpx _APP_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "CostReview", "app")) _COPY_IGNORE = shutil.ignore_patterns("__pycache__", "_deprecated", "tests", "输出") def _free_port(): s = socket.socket() s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] s.close() return port class Server: """隔离后台。用法:with Server(log_path) as srv: ...""" def __init__(self, log_path): self.log_path = log_path self.root = None self.proc = None self.port = None self.base = None self.client = None # ---------------------------------------------------------------- 生命周期 def __enter__(self): import config self.root = tempfile.mkdtemp(prefix="jmtj_server_") # 临时目录(退出时整体删除) app_dst = os.path.join(self.root, "CostReview", "app") shutil.copytree(_APP_SRC, app_dst, ignore=_COPY_IGNORE) src_dir = os.path.join(self.root, "后台需要导入的项目") os.makedirs(src_dir) lic = os.path.join(self.root, "lic") os.makedirs(lic) with open(os.path.join(lic, "config.json"), "w", encoding="utf-8") as f: f.write('{"enforce": false}') self.port = _free_port() self.base = "http://127.0.0.1:%d" % self.port env = dict(os.environ, PR_PORT=str(self.port), LICENSE_DATA_DIR=lic, PYTHONIOENCODING="utf-8") log = open(self.log_path, "wb") self.proc = subprocess.Popen( [sys.executable, "run_server_headless.py"], cwd=app_dst, env=env, stdout=log, stderr=subprocess.STDOUT) self.client = httpx.Client(base_url=self.base, timeout=60) deadline = time.time() + config.SERVER_READY while time.time() < deadline: try: if self.client.get("/api/license/status").status_code == 200: return self except Exception: if self.proc.poll() is not None: raise RuntimeError("后台进程启动即退出,日志见 " + self.log_path) time.sleep(0.3) self.stop() raise RuntimeError("后台 %ds 未就绪,日志见 %s" % (config.SERVER_READY, self.log_path)) def __exit__(self, *exc): self.stop() def stop(self): if self.client: self.client.close() self.client = None if self.proc: self.proc.terminate() try: self.proc.wait(10) except Exception: self.proc.kill() self.proc = None if self.root: shutil.rmtree(self.root, ignore_errors=True) self.root = None # ---------------------------------------------------------------- 请求小助手 @property def src_dir(self): return os.path.join(self.root, "后台需要导入的项目") def get(self, path, **params): r = self.client.get(path, params=params) assert r.status_code == 200, "%s -> HTTP %d: %s" % (path, r.status_code, r.text[:200]) return r.json() def post(self, path, body): r = self.client.post(path, json=body) assert r.status_code == 200, "%s -> HTTP %d: %s" % (path, r.status_code, r.text[:200]) return r.json()