Files

50 lines
1.6 KiB
Python

"""复现门户脚本里的请求签名。"""
from __future__ import annotations
import hashlib
import time
import uuid
from urllib.parse import quote
from app.platform.constants import APP_KEY, APP_SECRET, SIGN_VERSION
_SKIP = {"sign", "SIG", "UPPER_SIG"}
def encode_uri_component(value: str) -> str:
return quote(value, safe="-_.!~*'()")
def build_sign(
params: dict | None = None,
*,
encode: bool = True,
timestamp: str | None = None,
nonce: str | None = None,
) -> dict[str, str]:
"""与页面 Ll() 一致:参数按键名排序后拼接,再 MD5 大写。"""
stamp = timestamp if timestamp is not None else str(int(time.time()))
nonce_str = nonce if nonce is not None else uuid.uuid4().hex
payload: dict[str, str] = {}
for key, value in (params or {}).items():
text = "" if value is None else str(value)
payload[str(key)] = text if text == "" or not encode else encode_uri_component(text)
payload["timestamp"] = stamp
payload["nonceStr"] = nonce_str
payload["version"] = SIGN_VERSION
raw = "".join(f"{key}{payload[key]}" for key in sorted(payload) if key not in _SKIP)
sign = hashlib.md5((raw + APP_SECRET).encode("utf-8")).hexdigest().upper()
return {
"sign": sign,
"timestamp": stamp,
"nonceStr": nonce_str,
"version": SIGN_VERSION,
"appKey": APP_KEY,
}
def wfs_sig(service_code: str) -> str:
"""WFS/WMS 的 sig 是 md5(服务编码 + secret),十六进制小写。"""
return hashlib.md5((service_code + APP_SECRET).encode("utf-8")).hexdigest()