unis-oa/backend/scripts/pms_balance_stub.py

99 lines
4.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""PMS 预算余额的假上游:三个项目三个余额,拿来顶替还没开发完的真接口。
cd backend && python3 scripts/pms_balance_stub.py # 默认 9099
python3 scripts/pms_balance_stub.py --port 9100
数据源那边把通道改成「调外部接口」、地址填 http://127.0.0.1:9099/budget/balance 就能用,
入参名照数据源「入参」页配的 ``project_code`` 发(POST + JSON)。响应外壳与样例响应一致:
``{"code": 0, "message": "ok", "data": {"balance": ...}}``。
为什么不用「样例数据」那个通道:它一份响应是写死的,不认入参,三个项目只能拿到同一个数。
这里按 project_code 查表,顺带回两种业务错误,把「余额不足」和「取不到数」两条路一次测全。
"""
from __future__ import annotations
import argparse
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
#: 三个项目,故意给三种下场:充足、一超就挡、零余额
BALANCES = {
"P00001": 128000.00, # 项目1:宽裕,正常放行
"P00002": 5000.00, # 项目2:小额,随便报一点就超
"P00003": 0.00, # 项目3:没预算
}
PATH = "/budget/balance"
def answer(code: int, message: str, data=None) -> dict:
return {"code": code, "message": message, "data": data}
def lookup(project_code: object) -> dict:
"""按项目编码回一份响应,两种业务错误也走 200 + code 非 0,跟真接口的常见做法一致。"""
key = str(project_code or "").strip()
if not key:
# 表单上的入参名与数据源声明的对不上时就会走到这里,是最有价值的一条报错
return answer(4001, "项目编码不能为空,检查字段上的取数入参名")
if key not in BALANCES:
return answer(4004, f"项目 {key} 不存在或未立项")
return answer(0, "ok", {"projectCode": key, "balance": BALANCES[key]})
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_POST(self) -> None: # noqa: N802
if self.path.split("?")[0] != PATH:
return self.send(404, answer(404, f"没有这个路径:{self.path}"))
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length).decode("utf-8") if length else ""
try:
body = json.loads(raw or "{}")
except ValueError:
return self.send(400, answer(400, "请求体不是合法 JSON"))
payload = lookup(body.get("project_code"))
print(f" 入 {json.dumps(body, ensure_ascii=False)} -> code={payload['code']} "
f"balance={((payload.get('data') or {}).get('balance'))}", flush=True)
self.send(200, payload)
def do_GET(self) -> None: # noqa: N802 方便浏览器与 curl 直接点一下
if self.path.split("?")[0] != PATH:
return self.send(404, answer(404, f"没有这个路径:{self.path}"))
query = self.path.split("?", 1)[1] if "?" in self.path else ""
code = dict(pair.split("=", 1) for pair in query.split("&") if "=" in pair).get("project_code", "")
payload = lookup(code)
print(f" 入 GET project_code={code!r} -> code={payload['code']}", flush=True)
self.send(200, payload)
def send(self, status: int, payload: dict) -> None:
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *_args) -> None:
pass # 默认那套 stderr 日志太吵,上面自己打
def main() -> None:
parser = argparse.ArgumentParser(description="PMS 预算余额假上游")
parser.add_argument("--port", type=int, default=9099)
args = parser.parse_args()
server = ThreadingHTTPServer(("0.0.0.0", args.port), Handler)
print(f"PMS 假上游已启动:POST http://127.0.0.1:{args.port}{PATH}")
for code, balance in BALANCES.items():
print(f" {code} -> {balance:,.2f}")
print(" 其它编码 -> code=4004 项目不存在;空编码 -> code=4001")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n已停止")
if __name__ == "__main__":
main()