新增美团 CPS 券定时抓取入库(北京试点),作为"销量/佣金排序"的本地数据源 (#38)

Co-authored-by: chenshuobo <1119780489@qq.com>
Reviewed-on: #38
This commit was merged in pull request #38.
This commit is contained in:
2026-06-10 18:34:40 +08:00
parent 0890e693d7
commit 455884401f
6 changed files with 213 additions and 5 deletions
+11 -3
View File
@@ -22,6 +22,7 @@ import hashlib
import os
import re
import sys
import tempfile
import time
from datetime import datetime, timedelta, timezone
@@ -44,7 +45,10 @@ PAGE_SIZE = 20
MAX_PAGES = 80 # 单路安全上限(搜索 ~52 页、供给 ~70 页)
PAGE_SLEEP = 0.35 # 页间配速,缓解 402
RETRY = 7
LOCK_FILE = "data/.meituan_etl.lock"
# 运行锁默认放系统临时目录(任何账号可写),不依赖代码目录 data/ 的写权限——
# 无 sudo 部署时 data/ 常属 root,cps 写不了会导致每轮 PermissionError、cron 抓不进数据。
# 需要指定位置时用环境变量 MEITUAN_ETL_LOCK 覆盖。
LOCK_FILE = os.environ.get("MEITUAN_ETL_LOCK") or os.path.join(tempfile.gettempdir(), "meituan_etl.lock")
LOCK_STALE_SEC = 30 * 60 # 锁超过 30min 视为陈旧(进程异常退出残留),自动接管
SOURCES = [
@@ -288,8 +292,10 @@ def run_once(prune_hours: int = 24) -> None:
total += up
print(f" {src['label']:18}{len(items):5} 解析{len(parsed):5} "
f"入库{up:5} (本源去重{dup:3}) {time.time() - ts:4.0f}s")
# 清理长期未再出现的陈旧券(美团 sign 轮换 / 券下架后的残留),默认 24h 宽限
if prune_hours and prune_hours > 0:
# 清理长期未再出现的陈旧券(美团 sign 轮换 / 券下架后的残留),默认 24h 宽限
# 护栏:仅在本轮确有入库(total>0)时才清理。美团整体故障时本轮可能 0 入库
# (脚本不抛异常、只是抓回空),若仍照常 prune,连续故障会按 last_seen 把全表删空。
if prune_hours and prune_hours > 0 and total > 0:
cutoff = now - timedelta(hours=prune_hours)
pruned = db.execute(
delete(MeituanCoupon).where(MeituanCoupon.last_seen < cutoff)
@@ -297,6 +303,8 @@ def run_once(prune_hours: int = 24) -> None:
db.commit()
if pruned:
print(f" 清理陈旧券(>{prune_hours}h 未再出现): {pruned}")
elif prune_hours and prune_hours > 0 and total == 0:
print(" 本轮 0 入库(疑似上游故障),跳过清理以防误删全表")
cnt = db.execute(select(func.count()).select_from(MeituanCoupon)).scalar()
print(f"[{datetime.now():%H:%M:%S}] 本轮完成: 入库 {total} 条, 表总计 {cnt} 行, "
f"用时 {time.time() - t0:.0f}s")