procurement-crawler-py / bench_api.py
cormort's picture
perf(api): 減少 90% 請求數、支援 Token 與快取,並修好會讓頁面崩潰的錯誤處理
9390e47 verified
Raw History Blame Contribute Delete
5.54 kB
"""舊做法 vs 新做法的實測對照(會打真實 API,請禮貌執行)。
跑法:
python3 bench_api.py # 預設 10 筆
python3 bench_api.py 20
量什麼:
A. 舊做法:搜尋 1 次 + 逐筆 `/api/tender`(原程式的流程,沒有客戶端限速)→ 請求數、429 次數、耗時
B. 新做法:搜尋 1 次(帶 columns[])→ 請求數、耗時、拿到幾個詳細欄位
C. 完整欄位:新做法下逐筆取 86 欄(有客戶端限速)→ 驗證欄位數與 Excel 產出
注意:pcc-api 的速率限制是「10 秒 >10 次或 60 秒 >60 次就 429」,所以 A 很容易被擋
——那正是原程式在真實使用時會遇到的狀況(429 之後使用者只看到失敗訊息)。
"""
import sys
import time
import requests
from pcc_core import LIST_COLUMNS, PccApi, RateLimiter, flatten_detail
COUNT = int(sys.argv[1]) if len(sys.argv) > 1 else 10
QUERY = "農田水利署"
def pick_targets(count: int) -> list[dict]:
payload = requests.get(f"https://pcc-api.openfun.app/api/searchbytitle",
params={"query": QUERY, "page": 1}, timeout=25).json()
return (payload.get("records") or [])[:count]
def old_way(targets: list[dict]) -> dict:
"""原程式流程:搜尋一次(不帶 columns),再逐筆打 /api/tender,無客戶端限速。"""
started = time.time()
requests_made, blocked, ok = 0, 0, 0
for item in targets:
url = f"https://pcc-api.openfun.app/api/tender?unit_id={item['unit_id']}&job_number={item['job_number']}"
response = requests.get(url, timeout=20)
requests_made += 1
if response.status_code == 429:
blocked += 1
continue
detail = (response.json().get("records") or [{}])[0].get("detail", {})
if detail:
ok += 1
time.sleep(0.05) # 原程式沒有延遲;這裡只留一點避免瞬間灌爆
return {"requests": requests_made, "blocked": blocked, "ok": ok, "seconds": time.time() - started}
def new_way(targets: list[dict]) -> dict:
"""新做法:一次搜尋請求就把整頁加上指定的詳細欄位帶回來。"""
api = PccApi() # 內建自我限速
started = time.time()
payload = api.search_by_title(QUERY, 1, LIST_COLUMNS)
seconds = time.time() - started
records = payload.get("records") or []
with_detail = sum(1 for r in records if r.get("detail"))
sample = next((r for r in records if r.get("detail")), {}).get("detail", {})
return {
"requests": api.requests_made,
"records": len(records),
"with_detail": with_detail,
"columns": len(sample),
"seconds": seconds,
"sample": sample,
}
def full_detail(targets: list[dict]) -> dict:
"""新做法下的「完整欄位」:逐筆取 86 欄(有客戶端限速,因此不會被 429)。"""
limiter = RateLimiter()
api = PccApi(limiter=limiter)
started = time.time()
rows, blocked = [], 0
for item in targets[:3]: # 只抽 3 筆示範
try:
payload = api.tender(item["unit_id"], item["job_number"])
except Exception as exc: # noqa: BLE001
blocked += 1
print(" 失敗:", exc)
continue
records = payload.get("records") or []
if records:
rows.append(flatten_detail(records[0].get("detail", {})))
return {
"requests": api.requests_made,
"rows": len(rows),
"fields": len(rows[0]) if rows else 0,
"seconds": time.time() - started,
"waited": limiter.waited,
}
def main() -> None:
print(f"=== 取樣:{QUERY} 前 {COUNT} 筆 ===")
targets = pick_targets(COUNT)
print(f"取得 {len(targets)} 筆標的(此請求本身不算在比較內)\n")
old = old_way(targets)
print("【舊做法】搜尋 + 逐筆 /api/tender(無客戶端限速)")
print(f" 請求 {old['requests']} 次|成功 {old['ok']} 筆|被 429 擋 {old['blocked']} 次|耗時 {old['seconds']:.1f}s")
print(f" 每次請求平均 {old['seconds'] / max(1, old['requests']):.2f}s\n")
# 讓 10 秒窗口清空,避免把前一段的 429 狀態帶進下一段
print("(等待 15 秒讓 API 的限速窗口清空…)")
time.sleep(15)
new = new_way(targets)
print("【新做法】一次搜尋請求(帶 columns[])")
print(f" 請求 {new['requests']} 次|回傳 {new['records']} 筆(其中 {new['with_detail']} 筆含詳細欄位)"
f"|耗時 {new['seconds']:.1f}s")
print(f" 單筆帶回欄位數:{new['columns']}")
if new["sample"]:
for key, value in list(new["sample"].items())[:6]:
print(f" {key} = {value}")
print()
print("(等待 15 秒…)")
time.sleep(15)
full = full_detail(targets)
print("【新做法】完整欄位(86 欄,逐筆、有限速)")
print(f" 請求 {full['requests']} 次|{full['rows']} 列 × {full['fields']} 欄|耗時 {full['seconds']:.1f}s"
f"(限速等待 {full['waited']:.1f}s)")
print()
print("=== 結論 ===")
saved = old["requests"] - new["requests"]
print(f" 同樣取得 {len(targets)} 筆的金額/截止日:舊做法 {old['requests']} 次請求(其中 {old['blocked']} 次被擋),"
f"新做法 {new['requests']} 次 → 省下 {saved} 次({(1 - new['requests'] / max(1, old['requests'])) * 100:.0f}%)")
if __name__ == "__main__":
main()