AutoRpa/rpa_cart/yaoex_client.py

95 lines
2.8 KiB
Python
Raw Permalink 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.

# 1 号药城订单导出。
from __future__ import annotations
import json
import time
from datetime import date, datetime, timedelta
from typing import Any
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
GATEWAY = "https://gateway-b2b.fangkuaiyi.com"
EXPORT_URL = f"{GATEWAY}/api/order/export"
# 导出用的起止时间。默认只含当天,从 0 点到 23:59:59。
def day_range(day: date | None = None, days: int = 0) -> tuple[str, str]:
end = day or date.today()
start = end - timedelta(days=max(days, 0))
return (
datetime.combine(start, datetime.min.time()).strftime("%Y-%m-%d 00:00:00"),
f"{end.isoformat()} 23:59:59",
)
# 按时间段导出 1 号药城订单明细,返回 Excel 字节。回包不是表格就失败。
def export_orders(
token: str,
*,
begin: str,
end: str,
session: requests.Session | None = None,
) -> bytes:
params = {
"queryHistory": "false",
"productName": "",
"supplyName": "",
"flowId": "",
"createBeginTime": begin,
"createEndTime": end,
"orderStatus": 0,
}
own = session is None
client = session or requests.Session()
try:
response = client.post(
EXPORT_URL,
data=_form(token, {"jsonParams": json.dumps(params, ensure_ascii=False)}),
headers=_headers(),
timeout=180,
verify=False,
)
response.raise_for_status()
if "json" in (response.headers.get("content-type") or "") and response.content[:2] != b"PK":
raise RuntimeError(f"导出失败:{response.text[:300]}")
if response.content[:8] != b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" and response.content[:2] != b"PK":
head = response.content[:80]
raise RuntimeError(f"导出不是 Excel:{head!r}")
return response.content
finally:
if own:
client.close()
# 拼 1 号药城导出表单,带上登录 token。
def _form(token: str, extra: dict[str, Any]) -> dict[str, Any]:
payload = {
"traderName": "yaoex_pc",
"trader": "pc",
"closesignature": "yes",
"signature_method": "md5",
"signature": "****",
"timestamp": str(int(time.time() * 1000)),
"token": token,
"userToken": token,
}
payload.update(extra)
return payload
# 1 号药城订单导出请求头。来源页是订单列表。
def _headers() -> dict[str, str]:
return {
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "XMLHttpRequest",
"X-Request-Agent": "Axios",
"traderName": "yaoex_pc",
"trader": "pc",
"Origin": "https://mall.yaoex.com",
"Referer": "https://mall.yaoex.com/v2/orderList/",
}