upload
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
# ────────────────────────────────────────────────────────────────────────
|
||||
# 后端环境配置模板:复制为 backend/.env 并填写真实密码
|
||||
# Windows: copy backend\.env.example backend\.env
|
||||
# Linux: cp backend/.env.example backend/.env
|
||||
# .env 含数据库密码,不要提交到仓库、不要外传
|
||||
# ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# 主库(只读):mt_hotel(hotel_task / hotel_json)、area_crood(area_info)
|
||||
# 密码中的特殊字符需 URL 编码:@ → %40、! → %21、# → %23
|
||||
MAIN_DB_URL=mysql+aiomysql://root:密码@183.6.7.91:33016/mt_hotel?charset=utf8mb4
|
||||
|
||||
# 抓包库(仅可写 hotel_hd 的 city / prox / is_ok)
|
||||
HEADERS_DB_URL=mysql+aiomysql://root:密码@192.168.5.2:3307/headers_project?charset=utf8mb4
|
||||
|
||||
# 埋点与审计日志目录(相对 backend/ 解析;../../logs 指向 酒店/logs)
|
||||
LOG_DIR=../../logs
|
||||
|
||||
# 前端开发源(多源用英文逗号分隔)
|
||||
CORS_ORIGINS=http://localhost:5175,http://127.0.0.1:5175
|
||||
|
||||
# 任务平台 OpenAPI(只读接口)
|
||||
HOTEL_PLATFORM_BASE=http://ktl-001.dsfdl-henan.xyz/openApi
|
||||
HOTEL_PLATFORM_USER=thzn-datagram0001
|
||||
HOTEL_PLATFORM_PWD=密码
|
||||
HOTEL_PLATFORM_VENDOR=mt-datagram
|
||||
HOTEL_PLATFORM_TIMEOUT=12
|
||||
HOTEL_PLATFORM_CACHE=60
|
||||
@@ -0,0 +1,2 @@
|
||||
# hotel dashboard backend package
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""全局配置:双数据源 + 日志目录 + 任务平台 OpenAPI + 采集脚本(读取 backend/.env)。"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
BACKEND_DIR = Path(__file__).resolve().parent.parent
|
||||
load_dotenv(BACKEND_DIR / ".env")
|
||||
|
||||
# ── 数据源 ──────────────────────────────────────────────────────────────
|
||||
# 主库(只读):mt_hotel.hotel_task / hotel_json,area_crood.area_info
|
||||
MAIN_DB_URL = os.getenv(
|
||||
"MAIN_DB_URL",
|
||||
"mysql+aiomysql://root@127.0.0.1:3306/mt_hotel?charset=utf8mb4",
|
||||
)
|
||||
# 抓包库(可写 hotel_hd 的 city/prox/is_ok):headers_project.hotel_hd、project_proxy.proxs_list
|
||||
HEADERS_DB_URL = os.getenv(
|
||||
"HEADERS_DB_URL",
|
||||
"mysql+aiomysql://root@127.0.0.1:3307/headers_project?charset=utf8mb4",
|
||||
)
|
||||
|
||||
# ── 日志目录(可配置多个,英文分号分隔;采集脚本在哪儿跑,就把它的 logs 目录加进来)
|
||||
# 例:LOG_DIR=../../logs;C:\Users\lkq\Desktop\lkq\酒店9\酒店\logs
|
||||
# 第一个目录同时用于写审计文件(audit.jsonl)
|
||||
def _resolve_dir(raw: str):
|
||||
p = Path(raw.strip())
|
||||
return p.resolve() if p.is_absolute() else (BACKEND_DIR / p).resolve()
|
||||
|
||||
|
||||
LOG_DIRS = [d for d in (_resolve_dir(x) for x in os.getenv("LOG_DIR", "../../logs").split(";")) if str(d)]
|
||||
if not LOG_DIRS:
|
||||
LOG_DIRS = [(BACKEND_DIR / "../../logs").resolve()]
|
||||
LOG_DIR = LOG_DIRS[0] # 审计写入目录(兼容旧代码)
|
||||
|
||||
# ── CORS ────────────────────────────────────────────────────────────────
|
||||
CORS_ORIGINS = [
|
||||
o.strip()
|
||||
for o in os.getenv(
|
||||
"CORS_ORIGINS", "http://localhost:5175,http://127.0.0.1:5175"
|
||||
).split(",")
|
||||
if o.strip()
|
||||
]
|
||||
|
||||
# ── 业务常量 ────────────────────────────────────────────────────────────
|
||||
HOTEL_TITLE_LIKE = "%美团酒店详情%" # hotel_hd 取数条件,与采集脚本 get_headers() 一致
|
||||
|
||||
# ── 任务平台 OpenAPI(只读:getStats / realtimeCityList / realtimeCheckInOutDateList)──
|
||||
PLATFORM_BASE = os.getenv("HOTEL_PLATFORM_BASE", "http://ktl-001.dsfdl-henan.xyz/openApi")
|
||||
PLATFORM_USER = os.getenv("HOTEL_PLATFORM_USER", "thzn-datagram0001")
|
||||
PLATFORM_PWD = os.getenv("HOTEL_PLATFORM_PWD", "")
|
||||
PLATFORM_VENDOR = os.getenv("HOTEL_PLATFORM_VENDOR", "mt-datagram")
|
||||
PLATFORM_TIMEOUT = int(os.getenv("HOTEL_PLATFORM_TIMEOUT", "12"))
|
||||
PLATFORM_CACHE_SECONDS = int(os.getenv("HOTEL_PLATFORM_CACHE", "60"))
|
||||
|
||||
# ── 采集端(酒店详情.py):页面上的「启动采集」按钮 ─────────────────────
|
||||
# 默认就是本仓库上一级(酒店-lkq/),脚本和 logs/ 都在那里
|
||||
COLLECTOR_DIR = Path(os.getenv("HOTEL_COLLECTOR_DIR") or (BACKEND_DIR / "../..")).resolve()
|
||||
COLLECTOR_SCRIPT = os.getenv("HOTEL_COLLECTOR_SCRIPT", "酒店详情.py")
|
||||
COLLECTOR_PYTHON = os.getenv("HOTEL_COLLECTOR_PYTHON") or sys.executable
|
||||
COLLECTOR_PID_FILE = COLLECTOR_DIR / "logs" / "collector.pid"
|
||||
COLLECTOR_LOG_FILE = COLLECTOR_DIR / "logs" / "collector.out.log"
|
||||
@@ -0,0 +1,23 @@
|
||||
"""两个异步数据库引擎。
|
||||
|
||||
- main_engine : 183.6.7.91:33016(mt_hotel / area_crood)—— 只读
|
||||
- headers_engine : 192.168.5.2:3307(headers_project / project_proxy)—— 仅写 hotel_hd 的 city/prox/is_ok
|
||||
"""
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||
|
||||
from .config import HEADERS_DB_URL, MAIN_DB_URL
|
||||
|
||||
|
||||
def _make_engine(url: str) -> AsyncEngine:
|
||||
return create_async_engine(
|
||||
url,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=3600,
|
||||
pool_size=5,
|
||||
max_overflow=5,
|
||||
)
|
||||
|
||||
|
||||
main_engine: AsyncEngine = _make_engine(MAIN_DB_URL)
|
||||
headers_engine: AsyncEngine = _make_engine(HEADERS_DB_URL)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""美团酒店任务看板 API 入口。
|
||||
|
||||
启动:python start.py(根目录)或 cd backend && uvicorn app.main:app --port 8011
|
||||
静态托管:若 frontend/dist 存在,则页面由后端一并托管(--static 模式)。
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .config import CORS_ORIGINS
|
||||
from .routers import accounts, alerts, audit, collector, health, meta, overview, platform, records, stats
|
||||
|
||||
app = FastAPI(title="美团酒店任务看板 API", version="1.0.0")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=CORS_ORIGINS,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(meta.router)
|
||||
app.include_router(overview.router)
|
||||
app.include_router(stats.router)
|
||||
app.include_router(accounts.router)
|
||||
app.include_router(records.router)
|
||||
app.include_router(alerts.router)
|
||||
app.include_router(platform.router)
|
||||
app.include_router(collector.router)
|
||||
app.include_router(audit.router)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
|
||||
"""把 HTTPException(detail=...) 统一成 {code, msg, data} 顶层结构(见 04 文档 4 节)。"""
|
||||
detail = exc.detail
|
||||
if isinstance(detail, dict) and "code" in detail:
|
||||
body = {"code": detail.get("code"), "msg": detail.get("msg", ""), "data": None}
|
||||
else:
|
||||
body = {"code": exc.status_code, "msg": str(detail), "data": None}
|
||||
return JSONResponse(status_code=exc.status_code, content=body)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
"""参数校验失败也走 {code, msg} 结构,避免前端拿到 FastAPI 原始 detail 数组。"""
|
||||
first = exc.errors()[0] if exc.errors() else {}
|
||||
loc = ".".join(str(x) for x in first.get("loc", []) if x != "body")
|
||||
msg = f"参数 {loc} 不合法:{first.get('msg', '')}".strip()
|
||||
return JSONResponse(status_code=422, content={"code": 422, "msg": msg, "data": None})
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
"""兜底:未捕获异常统一成 {code:-1, msg},不把堆栈暴露给前端。"""
|
||||
print(f"[error] {request.method} {request.url.path}: {type(exc).__name__}: {exc}", flush=True)
|
||||
return JSONResponse(status_code=500, content={"code": -1, "msg": f"服务内部错误:{type(exc).__name__}"})
|
||||
|
||||
|
||||
_STATIC_DIR = Path(
|
||||
os.getenv("STATIC_DIR") or Path(__file__).resolve().parent.parent.parent / "frontend" / "dist"
|
||||
)
|
||||
if _STATIC_DIR.is_dir():
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
app.mount("/", StaticFiles(directory=str(_STATIC_DIR), html=True), name="spa")
|
||||
print(f"[static] 托管前端产物: {_STATIC_DIR}")
|
||||
@@ -0,0 +1,2 @@
|
||||
# routers package
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""GET /api/hotel/accounts —— 账号池分页(筛选 / 排序 / 今日跑量合并)。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..services import hotel_logs, hotel_query, hotel_write
|
||||
from ..services.hotel_meta import legal_cities
|
||||
from ..services.hotel_write import WriteError
|
||||
from .common import api_error, parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["accounts"])
|
||||
|
||||
SORT_FIELDS = ("id", "today_fetch_task", "updated_at", "req_count", "current_count")
|
||||
|
||||
|
||||
class ChangeCityBody(BaseModel):
|
||||
city: str = Field(..., description="合法城市(不带「市」)")
|
||||
operator: str | None = Field("local", description="操作人标识")
|
||||
|
||||
|
||||
class ResetBody(BaseModel):
|
||||
operator: str | None = Field("local", description="操作人标识")
|
||||
|
||||
|
||||
@router.get("/accounts")
|
||||
async def list_accounts(
|
||||
date: str | None = Query(None, description="今日跑量所属日期,默认今天"),
|
||||
city: str | None = Query(None, description="绑定城市(不带「市」)"),
|
||||
status: list[str] | None = Query(None, description="可多值:NULL / 403 / 401 / 418 / 0 / 6 / OTHER"),
|
||||
keyword: str | None = Query(None, description="dfpid 包含匹配"),
|
||||
page: int = Query(1, ge=1),
|
||||
size: int = Query(20, ge=1, le=200),
|
||||
sort: str = Query("id"),
|
||||
order: str = Query("desc", pattern="^(asc|desc)$"),
|
||||
) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
if sort not in SORT_FIELDS:
|
||||
sort = "id"
|
||||
|
||||
events, log_meta = hotel_logs.read_day(day)
|
||||
by_hd = hotel_logs.aggregate_by_hd(events)
|
||||
|
||||
items, total = await hotel_query.account_rows(
|
||||
today_agg=by_hd,
|
||||
city=city or None,
|
||||
status=status or None,
|
||||
keyword=keyword or None,
|
||||
page=page,
|
||||
size=size,
|
||||
sort=sort,
|
||||
order=order,
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"logs_available": bool(log_meta.get("available")),
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.post("/accounts/{hd_id}/city")
|
||||
async def change_city(hd_id: int, body: ChangeCityBody) -> dict:
|
||||
"""改绑定城市,并**自动把该账号代理置为 NULL**(下次运行按新城市补 IP)。"""
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
legal = legal_cities(list(proxy_ips.keys()))
|
||||
try:
|
||||
data = await hotel_write.change_city(
|
||||
hd_id,
|
||||
body.city,
|
||||
legal_cities=legal,
|
||||
proxy_ips=proxy_ips,
|
||||
operator=(body.operator or "local"),
|
||||
)
|
||||
except WriteError as e:
|
||||
raise api_error(e.status, e.msg, code=e.code)
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
|
||||
|
||||
@router.post("/accounts/{hd_id}/reset")
|
||||
async def reset_account(hd_id: int, body: ResetBody) -> dict:
|
||||
"""单条重置 is_ok → NULL(放回可用池)。不提供批量接口。"""
|
||||
try:
|
||||
data = await hotel_write.reset_is_ok(hd_id, operator=(body.operator or "local"))
|
||||
except WriteError as e:
|
||||
raise api_error(e.status, e.msg, code=e.code)
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""GET /api/hotel/alerts —— 今日空任务 / 长期未活动 / 封禁清单。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query
|
||||
from ..services.hotel_meta import mask_dfpid
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["alerts"])
|
||||
|
||||
STALE_HOURS = 24
|
||||
EMPTY_LIMIT = 200
|
||||
|
||||
|
||||
@router.get("/alerts")
|
||||
async def get_alerts(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
|
||||
events, log_meta = hotel_logs.read_day(day)
|
||||
empty_events = [e for e in events if e.get("event") == "fetch_empty"]
|
||||
empty_events.sort(key=lambda e: str(e.get("ts") or ""), reverse=True)
|
||||
|
||||
raw_accounts = {r["id"]: r for r in await hotel_query.all_accounts_raw()}
|
||||
empty_items = []
|
||||
for e in empty_events[:EMPTY_LIMIT]:
|
||||
hd_id = e.get("hd_id")
|
||||
acc = raw_accounts.get(hd_id) or {}
|
||||
empty_items.append(
|
||||
{
|
||||
"ts": e.get("ts"),
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(acc.get("dfpid")) or (f"…{e['dfpid_tail']}" if e.get("dfpid_tail") else None),
|
||||
"bind_city": e.get("bind_city"),
|
||||
"target_city": e.get("target_city"),
|
||||
"code": e.get("code"),
|
||||
"message": e.get("msg"),
|
||||
}
|
||||
)
|
||||
|
||||
stale = await hotel_query.stale_accounts(hours=STALE_HOURS)
|
||||
blocked = await hotel_query.blocked_accounts()
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(log_meta.get("available")),
|
||||
"empty_fetch": empty_items,
|
||||
"stale": stale,
|
||||
"blocked": blocked,
|
||||
"counts": {
|
||||
"empty_fetch": len(empty_events),
|
||||
"stale": len(stale),
|
||||
"blocked": len(blocked),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"""GET /api/hotel/audit —— 读取写操作审计(logs/audit.jsonl 末尾 N 行)。"""
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["audit"])
|
||||
|
||||
|
||||
@router.get("/audit")
|
||||
async def get_audit(limit: int = Query(50, ge=1, le=500)) -> dict:
|
||||
items = hotel_logs.read_audit(limit=limit)
|
||||
return {"code": 0, "msg": "ok", "data": {"items": items, "count": len(items)}}
|
||||
@@ -0,0 +1,33 @@
|
||||
"""采集端(酒店详情.py)控制:状态 / 启动 / 停止。
|
||||
|
||||
只做"起停 + 看状态",不碰采集逻辑;真正的入库、领任务仍由脚本自己完成。
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..services import collector
|
||||
from .common import api_error
|
||||
|
||||
router = APIRouter(prefix="/api/hotel/collector", tags=["collector"])
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def collector_status() -> dict:
|
||||
return {"code": 0, "msg": "ok", "data": await run_in_threadpool(collector.status)}
|
||||
|
||||
|
||||
@router.post("/start")
|
||||
async def collector_start() -> dict:
|
||||
try:
|
||||
return {"code": 0, "msg": "ok", "data": await run_in_threadpool(collector.start)}
|
||||
except collector.CollectorError as e:
|
||||
raise api_error(e.status, e.msg)
|
||||
|
||||
|
||||
@router.post("/stop")
|
||||
async def collector_stop() -> dict:
|
||||
try:
|
||||
return {"code": 0, "msg": "ok", "data": await run_in_threadpool(collector.stop)}
|
||||
except collector.CollectorError as e:
|
||||
raise api_error(e.status, e.msg)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""路由公共工具:日期校验、统一错误、行转字典。"""
|
||||
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
|
||||
|
||||
def api_error(status: int, msg: str, code: int | None = None) -> HTTPException:
|
||||
"""统一错误响应:{code, msg}。code 默认与 HTTP 状态一致,业务码可单独指定。"""
|
||||
return HTTPException(status_code=status, detail={"code": code if code is not None else status, "msg": msg})
|
||||
|
||||
|
||||
def parse_date(value: str, name: str = "date") -> date:
|
||||
if not value or not DATE_RE.match(value):
|
||||
raise api_error(400, f"{name} 格式应为 YYYY-MM-DD")
|
||||
try:
|
||||
return date.fromisoformat(value)
|
||||
except ValueError:
|
||||
raise api_error(400, f"{name} 不是合法日期")
|
||||
|
||||
|
||||
def check_range(start: date, end: date) -> None:
|
||||
if start > end:
|
||||
raise api_error(400, "start 不能晚于 end")
|
||||
|
||||
|
||||
def row_dict(row) -> dict:
|
||||
"""SQLAlchemy Row -> 纯 JSON 字典(Decimal/date/datetime 序列化)。"""
|
||||
out = {}
|
||||
for k, v in dict(row._mapping).items():
|
||||
if v is None:
|
||||
out[k] = None
|
||||
elif isinstance(v, Decimal):
|
||||
out[k] = int(v) if v == v.to_integral_value() else float(v)
|
||||
elif isinstance(v, datetime):
|
||||
out[k] = v.strftime("%Y-%m-%d %H:%M:%S")
|
||||
elif isinstance(v, date):
|
||||
out[k] = v.isoformat()
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
@@ -0,0 +1,28 @@
|
||||
"""GET /api/health —— 双库连通 + 日志目录可写性。"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..database import headers_engine, main_engine
|
||||
from ..services import hotel_logs
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health() -> dict:
|
||||
data: dict = {"db_main": "down", "db_headers": "down"}
|
||||
try:
|
||||
async with main_engine.connect() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
data["db_main"] = "up"
|
||||
except Exception as e: # noqa: BLE001 健康检查永不抛
|
||||
data["db_main_error"] = str(e)[:200]
|
||||
try:
|
||||
async with headers_engine.connect() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
data["db_headers"] = "up"
|
||||
except Exception as e: # noqa: BLE001
|
||||
data["db_headers_error"] = str(e)[:200]
|
||||
data.update(hotel_logs.log_dir_info())
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""GET /api/hotel/meta —— 城市清单、合法城市白名单、is_ok 字典(5 分钟缓存)。"""
|
||||
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..config import HOTEL_TITLE_LIKE, PLATFORM_PWD
|
||||
from ..database import main_engine
|
||||
from ..services import hotel_query
|
||||
from ..services.hotel_meta import IS_OK_DICT, legal_cities
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["meta"])
|
||||
|
||||
_city_id_cache: dict = {"ts": 0.0, "map": {}}
|
||||
_meta_cache: dict = {"ts": 0.0, "data": None}
|
||||
CACHE_SECONDS = 300
|
||||
|
||||
|
||||
async def _city_id_map() -> dict[str, str]:
|
||||
"""城市名 → 美团 cityId(area_info,title 含"美团")。"""
|
||||
now = time.time()
|
||||
if now - _city_id_cache["ts"] < CACHE_SECONDS and _city_id_cache["map"]:
|
||||
return _city_id_cache["map"]
|
||||
sql = text(
|
||||
"SELECT cityName, MIN(CAST(cityId AS UNSIGNED)) AS cid "
|
||||
"FROM area_crood.area_info "
|
||||
"WHERE title LIKE :pat AND cityName IS NOT NULL AND cityName <> '' "
|
||||
"GROUP BY cityName"
|
||||
)
|
||||
try:
|
||||
async with main_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": "%美团%"})).fetchall()
|
||||
mapping = {r[0]: str(r[1]) for r in rows if r[1] is not None}
|
||||
_city_id_cache.update(ts=now, map=mapping)
|
||||
return mapping
|
||||
except Exception: # noqa: BLE001 字典缺失不阻塞页面
|
||||
return _city_id_cache["map"]
|
||||
|
||||
|
||||
async def _proxy_city_ips() -> dict[str, int]:
|
||||
"""每城可用代理 IP 数(复用数据访问层,避免两处 SQL)。"""
|
||||
return await hotel_query.proxy_city_ips()
|
||||
|
||||
|
||||
async def _account_city_counts() -> dict[str, int]:
|
||||
"""每城账号数(hotel_hd,取数条件与采集脚本一致)。"""
|
||||
return await hotel_query.city_account_counts()
|
||||
|
||||
|
||||
@router.get("/meta")
|
||||
async def get_meta() -> dict:
|
||||
now = time.time()
|
||||
if _meta_cache["data"] is not None and now - _meta_cache["ts"] < CACHE_SECONDS:
|
||||
return {"code": 0, "msg": "ok", "data": _meta_cache["data"]}
|
||||
|
||||
proxy_ips = await _proxy_city_ips()
|
||||
accounts = await _account_city_counts()
|
||||
city_ids = await _city_id_map()
|
||||
whitelist = legal_cities(list(proxy_ips.keys()))
|
||||
whitelist_set = set(whitelist)
|
||||
|
||||
all_cities = sorted(set(proxy_ips) | set(accounts))
|
||||
cities = [
|
||||
{
|
||||
"city": c,
|
||||
"proxy_ips": proxy_ips.get(c, 0),
|
||||
"accounts": accounts.get(c, 0),
|
||||
"city_id": city_ids.get(c),
|
||||
"legal": c in whitelist_set,
|
||||
}
|
||||
for c in all_cities
|
||||
]
|
||||
|
||||
data = {
|
||||
"cities": cities,
|
||||
"legal_cities": whitelist,
|
||||
"is_ok_dict": IS_OK_DICT,
|
||||
"platform_available": bool(PLATFORM_PWD),
|
||||
}
|
||||
_meta_cache.update(ts=now, data=data)
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
@@ -0,0 +1,62 @@
|
||||
"""GET /api/hotel/overview 与 /api/hotel/trend —— 池子健康度 + 今日跑量 + 平台对照。"""
|
||||
|
||||
from datetime import date as Date
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query, platform_api
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["overview"])
|
||||
|
||||
|
||||
@router.get("/overview")
|
||||
async def overview(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
|
||||
pool = await hotel_query.pool_stats()
|
||||
|
||||
events, log_meta = hotel_logs.read_day(day)
|
||||
agg = hotel_logs.aggregate(events)
|
||||
by_hd = hotel_logs.aggregate_by_hd(events)
|
||||
uploads = agg["upload_ok"] + agg["upload_fail"]
|
||||
|
||||
today = {
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"upload_fail": agg["upload_fail"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"success_rate": round(agg["upload_ok"] / uploads * 100, 1) if uploads else None,
|
||||
"active_accounts": len(by_hd),
|
||||
"last_event_at": agg["last_event_at"],
|
||||
}
|
||||
|
||||
platform = await platform_api.get_stats(day)
|
||||
today_tasks = await hotel_query.count_today("hotel_task", day)
|
||||
today_records = await hotel_query.count_today("hotel_json", day)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"pool": pool,
|
||||
"today": today,
|
||||
"logs_available": bool(log_meta.get("available")),
|
||||
"db_today": {"hotel_task": today_tasks, "hotel_json": today_records},
|
||||
"platform": platform,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/trend")
|
||||
async def trend(
|
||||
days: int = Query(7, ge=1, le=90),
|
||||
end: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
) -> dict:
|
||||
end_day = parse_date(end) if end else Date.today()
|
||||
start_day = end_day - timedelta(days=days - 1)
|
||||
items = hotel_logs.timeline(start_day, end_day)
|
||||
return {"code": 0, "msg": "ok", "data": {"start": start_day.isoformat(), "end": end_day.isoformat(), "items": items}}
|
||||
@@ -0,0 +1,244 @@
|
||||
"""任务平台 getStats 只读代理。
|
||||
|
||||
- GET /api/hotel/platform/stats:按日期(+可选城市)取 success / reject / remain
|
||||
- GET /api/hotel/platform/risk:所选日期各城市明细 + 昨日成功率(高危筛查)
|
||||
|
||||
不传 city 时按合法城市白名单逐个取并发汇总;上游失败只影响该城市条目,不影响整体。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import date as Date
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query, platform_api
|
||||
from ..services.hotel_meta import legal_cities
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["platform"])
|
||||
|
||||
CONCURRENCY = 5
|
||||
ABNORMAL_MIN_SAMPLE = 5 # 当日样本(成功+失败)> 该值且成功率为 0 → 判定“异常”
|
||||
|
||||
|
||||
@router.get("/platform/stats")
|
||||
async def platform_stats(
|
||||
date: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
city: str | None = Query(None, description="只取单个城市(不带「市」)"),
|
||||
) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
|
||||
if city:
|
||||
one = await platform_api.get_stats(day, city)
|
||||
item = {
|
||||
"city": city,
|
||||
"success": one.get("success"),
|
||||
"reject": one.get("reject"),
|
||||
"remain": one.get("remain"),
|
||||
"timeout": one.get("timeout"),
|
||||
"ok": one.get("ok"),
|
||||
"error": one.get("error"),
|
||||
}
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {"date": day.isoformat(), "ok": bool(one.get("ok")), "items": [item],
|
||||
"summary": _summarize([item]), "failed": [] if one.get("ok") else [city]},
|
||||
}
|
||||
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
cities = legal_cities(list(proxy_ips.keys()))
|
||||
|
||||
sem = asyncio.Semaphore(CONCURRENCY)
|
||||
|
||||
async def one(c: str) -> dict:
|
||||
async with sem:
|
||||
res = await platform_api.get_stats(day, c)
|
||||
return {
|
||||
"city": c,
|
||||
"success": res.get("success"),
|
||||
"reject": res.get("reject"),
|
||||
"remain": res.get("remain"),
|
||||
"timeout": res.get("timeout"),
|
||||
"ok": res.get("ok"),
|
||||
"error": res.get("error"),
|
||||
}
|
||||
|
||||
items = await asyncio.gather(*(one(c) for c in cities))
|
||||
failed = [i["city"] for i in items if not i.get("ok")]
|
||||
ok_any = any(i.get("ok") for i in items)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"ok": ok_any,
|
||||
"items": items,
|
||||
"summary": _summarize(items),
|
||||
"failed": failed,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _summarize(items: list[dict]) -> dict:
|
||||
def total(key: str):
|
||||
values = [i.get(key) for i in items if isinstance(i.get(key), (int, float))]
|
||||
return sum(values) if values else None
|
||||
|
||||
return {
|
||||
"success": total("success"),
|
||||
"reject": total("reject"),
|
||||
"remain": total("remain"),
|
||||
"timeout": total("timeout"),
|
||||
"cities": len(items),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/platform/risk")
|
||||
async def platform_risk(
|
||||
date: str | None = Query(None, description="基准日 YYYY-MM-DD(页面所选的日期),默认今天"),
|
||||
end: str | None = Query(None, description="兼容旧参数,含义同 date"),
|
||||
days: int = Query(1, ge=1, le=30, description="参考窗口天数,**不含基准日**;默认 1 = 只看昨日"),
|
||||
threshold: float = Query(75.0, ge=0, le=100, description="高危阈值(参考窗口成功率低于该值)"),
|
||||
min_sample: int = Query(5, ge=1, description="参考窗口样本总量下限,低于此数不做高危判定"),
|
||||
) -> dict:
|
||||
"""基准日各城市成功/失败 + 参考窗口(默认 = 昨日)成功率,一次返回。
|
||||
|
||||
⚠️ 平台 `getStats` 只保留最近两天(今天 / 昨天):更早的日期返回空数据,
|
||||
所以"近 N 天成功率"拿不到,页面上的对照口径收敛为**昨日成功率**(days=1)。
|
||||
日期参数优先取 `date`(前端日期选择),`end` 仅作兼容。
|
||||
|
||||
高危 = 昨日 (success+reject) >= min_sample 且成功率 < threshold。
|
||||
昨日完全没数据时不做高危判定(risk_rate 置空,basis=no_window_data)。
|
||||
"""
|
||||
anchor = date or end
|
||||
end_day = parse_date(anchor) if anchor else Date.today()
|
||||
window = [end_day - timedelta(days=i) for i in range(days, 0, -1)] # 参考窗口,不含基准日
|
||||
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
cities = legal_cities(list(proxy_ips.keys()))
|
||||
|
||||
sem = asyncio.Semaphore(12)
|
||||
|
||||
async def one(day: Date, city: str) -> dict:
|
||||
async with sem:
|
||||
return await platform_api.get_stats(day, city)
|
||||
|
||||
# 参考窗口(默认只有昨日):days × cities 次(历史日期命中 30 分钟缓存)
|
||||
hist_results = await asyncio.gather(*(one(d, c) for d in window for c in cities))
|
||||
hist: dict[str, list[int]] = {c: [0, 0] for c in cities} # city -> [success, reject]
|
||||
hist_data_days: dict[str, int] = {c: 0 for c in cities}
|
||||
for idx, res in enumerate(hist_results):
|
||||
city = cities[idx % len(cities)]
|
||||
if not res.get("ok"):
|
||||
continue
|
||||
# 平台对超出保留期的日期返回 success/reject = null(不是 0),不能算作"有数据"
|
||||
has_num = isinstance(res.get("success"), (int, float)) or isinstance(res.get("reject"), (int, float))
|
||||
hist[city][0] += res.get("success") or 0
|
||||
hist[city][1] += res.get("reject") or 0
|
||||
if has_num:
|
||||
hist_data_days[city] += 1
|
||||
|
||||
# 当天埋点日志:get_one_task 返回 False / code≠0 的城市(fetch_empty)
|
||||
events, log_meta = hotel_logs.read_day(end_day)
|
||||
city_events = hotel_logs.aggregate_by_city(events)
|
||||
logs_available = bool(log_meta.get("available"))
|
||||
|
||||
# 当天
|
||||
today_results = await asyncio.gather(*(one(end_day, c) for c in cities))
|
||||
|
||||
items: list[dict] = []
|
||||
for idx, city in enumerate(cities):
|
||||
hs, hr = hist[city]
|
||||
hist_total = hs + hr
|
||||
hist_rate = round(hs / hist_total * 100, 1) if hist_total else None
|
||||
|
||||
today_res = today_results[idx]
|
||||
# 保留 null(= 平台没有该日期的统计),不要兜底成 0,否则"没数据"会被读成"0 条完成"
|
||||
ts = today_res.get("success") if today_res.get("ok") else None
|
||||
tr = today_res.get("reject") if today_res.get("ok") else None
|
||||
today_total = (ts or 0) + (tr or 0)
|
||||
today_rate = round(ts / today_total * 100, 1) if ts is not None and today_total else None
|
||||
|
||||
# 当日异常:样本 > 5 且成功率为 0(一条都没成功)
|
||||
today_abnormal = bool(ts is not None and today_total > ABNORMAL_MIN_SAMPLE and ts == 0)
|
||||
|
||||
# 拿任务失败(埋点 fetch_empty)次数
|
||||
empty_count = int((city_events.get(city) or {}).get("fetch_empty", 0))
|
||||
|
||||
# 高危判定:**必须**基于参考窗口(默认昨日,样本 ≥ min_sample 且成功率 < threshold);
|
||||
# 窗口内没有数据的城市不能判高危(它们由"当日异常"口径负责),risk_rate 置空
|
||||
basis = "window" if hist_total > 0 else "no_window_data"
|
||||
risk_rate = hist_rate
|
||||
high_risk = hist_rate is not None and hist_total >= min_sample and hist_rate < threshold
|
||||
|
||||
items.append(
|
||||
{
|
||||
"city": city,
|
||||
"hist_success": hs,
|
||||
"hist_reject": hr,
|
||||
"hist_total": hist_total,
|
||||
"hist_rate": hist_rate,
|
||||
"hist_days_with_data": hist_data_days[city],
|
||||
"today_success": ts,
|
||||
"today_reject": tr,
|
||||
"today_rate": today_rate,
|
||||
"today_remain": today_res.get("remain") if today_res.get("ok") else None,
|
||||
"today_timeout": today_res.get("timeout") if today_res.get("ok") else None,
|
||||
"today_total": today_total,
|
||||
"today_abnormal": today_abnormal,
|
||||
"empty_fetch_count": empty_count,
|
||||
"risk_rate": risk_rate,
|
||||
"risk_basis": basis,
|
||||
"high_risk": high_risk,
|
||||
}
|
||||
)
|
||||
|
||||
# 高危置顶 → 其余按风险成功率升序 → 无数据最后
|
||||
def rank(x: dict) -> int:
|
||||
if x["risk_rate"] is None:
|
||||
return 2
|
||||
return 0 if x["high_risk"] else 1
|
||||
|
||||
items.sort(key=lambda x: (rank(x), x["risk_rate"] if x["risk_rate"] is not None else 999, -x["hist_total"]))
|
||||
|
||||
high_risk = [i for i in items if i["high_risk"]]
|
||||
abnormal = [i for i in items if i["today_abnormal"]]
|
||||
empty_cities = [i for i in items if i["empty_fetch_count"] > 0]
|
||||
available = await hotel_query.available_accounts()
|
||||
# 平台接口是否可用 / 该日期平台是否有统计(与"0 条完成"区分开)
|
||||
platform_ok = any(r.get("ok") for r in today_results)
|
||||
has_data = any(i["today_success"] is not None or i["today_reject"] is not None for i in items)
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": end_day.isoformat(),
|
||||
"platform_ok": platform_ok,
|
||||
"has_data": has_data,
|
||||
"window": {
|
||||
"start": window[0].isoformat(),
|
||||
"end": window[-1].isoformat(),
|
||||
"days": days,
|
||||
"exclude_today": True,
|
||||
},
|
||||
"threshold": threshold,
|
||||
"min_sample": min_sample,
|
||||
"abnormal_min_sample": ABNORMAL_MIN_SAMPLE,
|
||||
"high_risk": high_risk,
|
||||
"abnormal": abnormal,
|
||||
"items": items,
|
||||
"logs_available": logs_available,
|
||||
"empty_fetch_total": sum(i["empty_fetch_count"] for i in items),
|
||||
"available_packages": available,
|
||||
"counts": {
|
||||
"cities": len(cities),
|
||||
"high_risk": len(high_risk),
|
||||
"abnormal": len(abnormal),
|
||||
"empty_fetch_cities": len(empty_cities),
|
||||
"available_packages": len(available),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"""任务记录 / 采集记录查询与采集详情解析。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_query
|
||||
from ..services.record_parser import parse_record, raw_preview
|
||||
from .common import api_error, check_range, parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["records"])
|
||||
|
||||
|
||||
def _range(start: str | None, end: str | None) -> tuple[Date, Date]:
|
||||
end_day = parse_date(end) if end else Date.today()
|
||||
start_day = parse_date(start) if start else end_day
|
||||
check_range(start_day, end_day)
|
||||
return start_day, end_day
|
||||
|
||||
|
||||
@router.get("/tasks")
|
||||
async def list_tasks(
|
||||
start: str | None = Query(None, description="YYYY-MM-DD,默认等于 end"),
|
||||
end: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
city: str | None = Query(None),
|
||||
keyword: str | None = Query(None, description="酒店名模糊 / unique_id 前缀"),
|
||||
page: int = Query(1, ge=1),
|
||||
size: int = Query(20, ge=1, le=200),
|
||||
) -> dict:
|
||||
start_day, end_day = _range(start, end)
|
||||
items, total = await hotel_query.tasks_page(
|
||||
start=start_day, end=end_day, city=city or None, keyword=keyword or None, page=page, size=size
|
||||
)
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"start": start_day.isoformat(),
|
||||
"end": end_day.isoformat(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"items": items,
|
||||
# hotel_task 的 hotel_id 上有唯一键:一行 = 一个酒店的最新快照
|
||||
"note": "按 created_at 过滤;hotel_task 每个酒店只保留一行(hotel_id UNIQUE)",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/records")
|
||||
async def list_records(
|
||||
start: str | None = Query(None, description="YYYY-MM-DD,默认等于 end"),
|
||||
end: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
city: str | None = Query(None),
|
||||
keyword: str | None = Query(None, description="酒店名模糊 / poi_id 前缀"),
|
||||
page: int = Query(1, ge=1),
|
||||
size: int = Query(20, ge=1, le=200),
|
||||
) -> dict:
|
||||
start_day, end_day = _range(start, end)
|
||||
items, total = await hotel_query.records_page(
|
||||
start=start_day, end=end_day, city=city or None, keyword=keyword or None, page=page, size=size
|
||||
)
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"start": start_day.isoformat(),
|
||||
"end": end_day.isoformat(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/records/{rec_id}")
|
||||
async def record_detail(rec_id: int) -> dict:
|
||||
row = await hotel_query.record_by_id(rec_id)
|
||||
if not row:
|
||||
raise api_error(404, f"采集记录 #{rec_id} 不存在", code=1004)
|
||||
|
||||
parsed = parse_record(row.get("json_data"))
|
||||
preview, truncated = raw_preview(row.get("json_data"))
|
||||
raw = row.get("json_data") or ""
|
||||
json_size = len(raw.encode("utf-8", errors="replace")) if isinstance(raw, str) else len(raw)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"id": row["id"],
|
||||
"hotel": {
|
||||
"poi_id": row.get("poi_id"),
|
||||
"city_id": row.get("city_id"),
|
||||
"hotel_name": row.get("hotel_name"),
|
||||
"city_name": row.get("city_name"),
|
||||
"check_in_date": row["check_in_date"].isoformat() if row.get("check_in_date") else None,
|
||||
"check_out_date": row["check_out_date"].isoformat() if row.get("check_out_date") else None,
|
||||
"create_at": row["create_at"].strftime("%Y-%m-%d %H:%M:%S") if row.get("create_at") else None,
|
||||
"json_size": json_size,
|
||||
},
|
||||
"parse_ok": parsed["parse_ok"],
|
||||
"structure": parsed["structure"],
|
||||
"error": parsed["error"],
|
||||
"rooms": parsed["rooms"],
|
||||
"min_price": parsed["min_price"],
|
||||
"raw_preview": preview,
|
||||
"raw_truncated": truncated,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"""GET /api/hotel/stats/account 与 /api/hotel/stats/city —— 今日跑量按账号/城市聚合。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query
|
||||
from ..services.hotel_meta import mask_dfpid
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel/stats", tags=["stats"])
|
||||
|
||||
|
||||
@router.get("/account")
|
||||
async def stats_account(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
"""每个账号今天跑了多少条(只含当日日志中出现过的账号)。"""
|
||||
day = parse_date(date) if date else Date.today()
|
||||
events, meta = hotel_logs.read_day(day)
|
||||
by_hd = hotel_logs.aggregate_by_hd(events)
|
||||
|
||||
raw = {r["id"]: r for r in await hotel_query.all_accounts_raw()}
|
||||
items: list[dict] = []
|
||||
for hd_id, agg in by_hd.items():
|
||||
acc = raw.get(hd_id) or {}
|
||||
items.append(
|
||||
{
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(acc.get("dfpid")),
|
||||
"city": acc.get("city"),
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"upload_fail": agg["upload_fail"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"last_event_at": agg["last_event_at"],
|
||||
"req_count": int(acc.get("req_count") or 0),
|
||||
"current_count": int(acc.get("current_count") or 0),
|
||||
}
|
||||
)
|
||||
items.sort(key=lambda x: (x["fetch_task"], x["last_event_at"] or ""), reverse=True)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(meta.get("available")),
|
||||
"bad_lines": meta.get("bad_lines", 0),
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/city")
|
||||
async def stats_city(
|
||||
date: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
top: int | None = Query(None, ge=1, le=200, description="只取跑量前 N 个城市"),
|
||||
) -> dict:
|
||||
"""每个城市跑了多少条(日志 target_city 聚合)+ 该城账号数与代理 IP 数。"""
|
||||
day = parse_date(date) if date else Date.today()
|
||||
events, meta = hotel_logs.read_day(day)
|
||||
by_city = hotel_logs.aggregate_by_city(events)
|
||||
|
||||
accounts = await hotel_query.city_account_counts()
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
|
||||
items: list[dict] = []
|
||||
for city in sorted(set(accounts) | set(proxy_ips) | set(by_city)):
|
||||
agg = by_city.get(city) or hotel_logs.empty_counter()
|
||||
items.append(
|
||||
{
|
||||
"city": city,
|
||||
"accounts": accounts.get(city, 0),
|
||||
"proxy_ips": proxy_ips.get(city, 0),
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"upload_fail": agg["upload_fail"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"last_event_at": agg["last_event_at"],
|
||||
}
|
||||
)
|
||||
items.sort(key=lambda x: (x["fetch_task"], x["accounts"]), reverse=True)
|
||||
if top:
|
||||
items = items[:top]
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(meta.get("available")),
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/failures")
|
||||
async def stats_failures(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
"""当天"拿任务失败"(埋点 fetch_empty)的城市清单。
|
||||
|
||||
用途:改/加城市的下拉框要把这些城市藏起来(绑过去也领不到任务)。
|
||||
"""
|
||||
day = parse_date(date) if date else Date.today()
|
||||
events, meta = hotel_logs.read_day(day)
|
||||
by_city = hotel_logs.aggregate_by_city(events)
|
||||
|
||||
items = [
|
||||
{
|
||||
"city": city,
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"last_event_at": agg["last_event_at"],
|
||||
}
|
||||
for city, agg in by_city.items()
|
||||
if agg["fetch_empty"] > 0
|
||||
]
|
||||
items.sort(key=lambda x: (-x["fetch_empty"], x["city"]))
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(meta.get("available")),
|
||||
"items": items,
|
||||
"cities": [i["city"] for i in items],
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# services package
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""采集进程(酒店详情.py)的启动 / 停止 / 状态。
|
||||
|
||||
设计要点:
|
||||
- 采集脚本自己把 pid 写进 `logs/collector.pid`,所以"控制台手动起的"也能识别,
|
||||
不会因为页面不知道就再起一个,导致两个进程抢同一个账号池;
|
||||
- 启动后 stdout/stderr 追加到 `logs/collector.out.log`,status 带最后几行方便排查;
|
||||
- 停止走 `taskkill /T /F`(Windows),避免 python 拉起子进程后残留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import (
|
||||
COLLECTOR_DIR,
|
||||
COLLECTOR_LOG_FILE,
|
||||
COLLECTOR_PID_FILE,
|
||||
COLLECTOR_PYTHON,
|
||||
COLLECTOR_SCRIPT,
|
||||
)
|
||||
|
||||
# Windows 进程创建标志
|
||||
CREATE_NEW_PROCESS_GROUP = 0x00000200
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
STILL_ACTIVE = 259
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
||||
|
||||
_proc: subprocess.Popen | None = None
|
||||
_started_at: float | None = None
|
||||
|
||||
|
||||
class CollectorError(Exception):
|
||||
"""业务错误,router 转成 {code,msg}。"""
|
||||
|
||||
def __init__(self, msg: str, status: int = 400):
|
||||
super().__init__(msg)
|
||||
self.msg = msg
|
||||
self.status = status
|
||||
|
||||
|
||||
def _pid_alive(pid: int | None) -> bool:
|
||||
if not pid or pid <= 0:
|
||||
return False
|
||||
if sys.platform == "win32":
|
||||
import ctypes
|
||||
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, int(pid))
|
||||
if not handle:
|
||||
return False
|
||||
try:
|
||||
code = ctypes.c_ulong()
|
||||
ok = kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
|
||||
return bool(ok) and code.value == STILL_ACTIVE
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
try:
|
||||
os.kill(int(pid), 0)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def read_pid() -> int | None:
|
||||
"""读 collector.pid(不存在 / 内容非法都返回 None)。"""
|
||||
try:
|
||||
text = COLLECTOR_PID_FILE.read_text(encoding="utf-8").strip()
|
||||
return int(text) if text else None
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _is_running(pid: int | None) -> bool:
|
||||
"""pid 是否还在跑。自己起的子进程用 Popen.poll() 判定(比 OpenProcess 准)。"""
|
||||
if not pid:
|
||||
return False
|
||||
if _proc is not None and _proc.pid == pid:
|
||||
return _proc.poll() is None
|
||||
return _pid_alive(pid)
|
||||
|
||||
|
||||
def current_pid() -> int | None:
|
||||
"""当前真正活着的采集进程 pid:优先 pid 文件(含手动启动),再看本进程的句柄。"""
|
||||
pid = read_pid()
|
||||
if pid and _is_running(pid):
|
||||
return pid
|
||||
if _proc is not None and _proc.poll() is None:
|
||||
return _proc.pid
|
||||
return None
|
||||
|
||||
|
||||
def tail(lines: int = 12) -> list[str]:
|
||||
try:
|
||||
with COLLECTOR_LOG_FILE.open("r", encoding="utf-8", errors="replace") as f:
|
||||
return [ln.rstrip() for ln in f.readlines()[-lines:]]
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
pid = current_pid()
|
||||
started: float | None = None
|
||||
if pid:
|
||||
if _proc is not None and _proc.pid == pid and _proc.poll() is None:
|
||||
started = _started_at
|
||||
else:
|
||||
try:
|
||||
started = COLLECTOR_PID_FILE.stat().st_mtime
|
||||
except OSError:
|
||||
started = None
|
||||
return {
|
||||
"running": bool(pid),
|
||||
"pid": pid,
|
||||
"source": "api" if (pid and _proc is not None and _proc.pid == pid) else ("manual" if pid else None),
|
||||
"started_at": datetime.fromtimestamp(started).strftime("%Y-%m-%d %H:%M:%S") if started else None,
|
||||
"uptime_seconds": int(time.time() - started) if started else None,
|
||||
"dir": str(COLLECTOR_DIR),
|
||||
"script": COLLECTOR_SCRIPT,
|
||||
"python": COLLECTOR_PYTHON,
|
||||
"log_file": str(COLLECTOR_LOG_FILE),
|
||||
"log_tail": tail(),
|
||||
}
|
||||
|
||||
|
||||
def start() -> dict:
|
||||
global _proc, _started_at
|
||||
|
||||
pid = current_pid()
|
||||
if pid:
|
||||
raise CollectorError(f"采集已经在运行(pid {pid}),不要重复启动", status=409)
|
||||
|
||||
script = COLLECTOR_DIR / COLLECTOR_SCRIPT
|
||||
if not script.is_file():
|
||||
raise CollectorError(f"找不到采集脚本:{script}", status=404)
|
||||
|
||||
COLLECTOR_LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_started_at = time.time()
|
||||
try:
|
||||
with COLLECTOR_LOG_FILE.open("a", encoding="utf-8", errors="replace") as out:
|
||||
out.write(f"\n===== 看板启动采集 {datetime.now():%Y-%m-%d %H:%M:%S} =====\n")
|
||||
out.flush()
|
||||
flags = CREATE_NEW_PROCESS_GROUP | (CREATE_NO_WINDOW if sys.platform == "win32" else 0)
|
||||
_proc = subprocess.Popen(
|
||||
[COLLECTOR_PYTHON, script.name],
|
||||
cwd=str(COLLECTOR_DIR),
|
||||
stdout=out,
|
||||
stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL,
|
||||
creationflags=flags if sys.platform == "win32" else 0,
|
||||
env={**os.environ, "PYTHONIOENCODING": "utf-8"},
|
||||
)
|
||||
except OSError as e: # 解释器不存在 / 权限不足
|
||||
_proc = None
|
||||
raise CollectorError(f"启动失败:{type(e).__name__}: {e}", status=500)
|
||||
|
||||
# 等两秒:脚本如果 import 就报错会立刻退出,这种情况直接把日志尾给它
|
||||
time.sleep(2.0)
|
||||
if _proc.poll() is not None:
|
||||
code = _proc.returncode
|
||||
_proc = None
|
||||
detail = "\n".join(tail(10)) or "(日志为空)"
|
||||
raise CollectorError(f"采集启动后立刻退出(exit={code}):\n{detail}", status=500)
|
||||
|
||||
return status()
|
||||
|
||||
|
||||
def _kill_pid(pid: int) -> None:
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
subprocess.run(
|
||||
["taskkill", "/T", "/F", "/PID", str(pid)],
|
||||
capture_output=True,
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass # taskkill 不可用就走后面的兜底
|
||||
else:
|
||||
try:
|
||||
os.kill(pid, 15)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def stop() -> dict:
|
||||
global _proc
|
||||
|
||||
pid = current_pid()
|
||||
if not pid:
|
||||
raise CollectorError("采集当前没有在运行", status=409)
|
||||
|
||||
mine = _proc is not None and _proc.pid == pid
|
||||
_kill_pid(pid)
|
||||
|
||||
for _ in range(30): # 最多等 6 秒
|
||||
if not _is_running(pid):
|
||||
break
|
||||
time.sleep(0.2)
|
||||
|
||||
# 兜底:自己起的子进程还没退,直接 TerminateProcess
|
||||
if _is_running(pid) and mine:
|
||||
try:
|
||||
_proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
|
||||
if _is_running(pid):
|
||||
raise CollectorError(f"停止失败,进程 {pid} 还在运行(可在任务管理器手动结束)", status=500)
|
||||
|
||||
_proc = None
|
||||
try:
|
||||
COLLECTOR_PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return status()
|
||||
@@ -0,0 +1,237 @@
|
||||
"""JSONL 日志读取与聚合(埋点事件 + 写操作审计)。
|
||||
|
||||
设计要点(对应 04 文档 6.3):
|
||||
- 按天分文件 `run_YYYYMMDD.jsonl`,只追加;坏行计数跳过,绝不抛 500
|
||||
- 缓存键 = (文件路径, st_mtime_ns, st_size),文件只增长,命中即复用
|
||||
- 文件/目录缺失 → 返回空集 + available=False,页面据此降级显示 "—"
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from ..config import LOG_DIR, LOG_DIRS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
AUDIT_FILE = "audit.jsonl"
|
||||
EVENTS = ("fetch_task", "fetch_empty", "upload", "exception")
|
||||
|
||||
# path(str) -> (mtime_ns, size, events, bad_lines)
|
||||
_cache: dict[str, tuple[int, int, list[dict], int]] = {}
|
||||
|
||||
|
||||
def run_log_path(day: date) -> Path:
|
||||
"""主日志目录(兼容旧调用)。"""
|
||||
return LOG_DIR / f"run_{day.strftime('%Y%m%d')}.jsonl"
|
||||
|
||||
|
||||
def run_log_paths(day: date) -> list[Path]:
|
||||
"""当天在所有配置目录下的候选文件(脚本可能在别的目录跑)。"""
|
||||
name = f"run_{day.strftime('%Y%m%d')}.jsonl"
|
||||
return [d / name for d in LOG_DIRS]
|
||||
|
||||
|
||||
def _parse_file(path: Path) -> tuple[list[dict], int]:
|
||||
"""读取并解析一个 JSONL 文件,返回 (events, bad_lines)。"""
|
||||
events: list[dict] = []
|
||||
bad = 0
|
||||
try:
|
||||
with path.open("r", encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except ValueError:
|
||||
bad += 1
|
||||
continue
|
||||
if isinstance(obj, dict) and obj.get("event"):
|
||||
events.append(obj)
|
||||
else:
|
||||
bad += 1
|
||||
except OSError:
|
||||
return [], 0
|
||||
return events, bad
|
||||
|
||||
|
||||
def read_day(day: date) -> tuple[list[dict], dict]:
|
||||
"""读取某天的事件(**合并所有配置的日志目录**)。
|
||||
|
||||
返回 (events, meta),meta 含 available / bad_lines / paths。
|
||||
"""
|
||||
events: list[dict] = []
|
||||
bad = 0
|
||||
paths: list[str] = []
|
||||
available = False
|
||||
|
||||
for path in run_log_paths(day):
|
||||
if not path.is_file():
|
||||
continue
|
||||
try:
|
||||
st = path.stat()
|
||||
except OSError:
|
||||
continue
|
||||
available = True
|
||||
paths.append(str(path))
|
||||
|
||||
key = str(path)
|
||||
cached = _cache.get(key)
|
||||
if cached and cached[0] == st.st_mtime_ns and cached[1] == st.st_size:
|
||||
events.extend(cached[2])
|
||||
bad += cached[3]
|
||||
continue
|
||||
|
||||
day_events, day_bad = _parse_file(path)
|
||||
_cache[key] = (st.st_mtime_ns, st.st_size, day_events, day_bad)
|
||||
events.extend(day_events)
|
||||
bad += day_bad
|
||||
|
||||
return events, {"available": available, "bad_lines": bad, "paths": paths}
|
||||
|
||||
|
||||
def read_range(start: date, end: date) -> tuple[list[dict], dict]:
|
||||
"""读取 [start, end] 区间事件(逐天文件依次读取)。"""
|
||||
events: list[dict] = []
|
||||
bad = 0
|
||||
any_available = False
|
||||
day = start
|
||||
while day <= end:
|
||||
day_events, meta = read_day(day)
|
||||
events.extend(day_events)
|
||||
bad += meta.get("bad_lines", 0)
|
||||
any_available = any_available or meta.get("available", False)
|
||||
day += timedelta(days=1)
|
||||
return events, {"available": any_available, "bad_lines": bad}
|
||||
|
||||
|
||||
# ── 聚合 ────────────────────────────────────────────────────────────────
|
||||
def empty_counter() -> dict:
|
||||
return {
|
||||
"fetch_task": 0,
|
||||
"upload_ok": 0,
|
||||
"upload_fail": 0,
|
||||
"fetch_empty": 0,
|
||||
"exception": 0,
|
||||
"last_event_at": None,
|
||||
}
|
||||
|
||||
|
||||
def _add(counter: dict, event: dict) -> None:
|
||||
name = event.get("event")
|
||||
if name == "upload":
|
||||
key = "upload_ok" if int(event.get("ok") or 0) == 1 else "upload_fail"
|
||||
counter[key] += 1
|
||||
elif name in ("fetch_task", "fetch_empty", "exception"):
|
||||
counter[name] += 1
|
||||
ts = event.get("ts")
|
||||
if isinstance(ts, str) and (counter["last_event_at"] is None or ts > counter["last_event_at"]):
|
||||
counter["last_event_at"] = ts
|
||||
|
||||
|
||||
def aggregate(events: list[dict]) -> dict:
|
||||
"""整体聚合(overview 用)。"""
|
||||
total = empty_counter()
|
||||
for ev in events:
|
||||
_add(total, ev)
|
||||
return total
|
||||
|
||||
|
||||
def aggregate_by_hd(events: list[dict]) -> dict[int, dict]:
|
||||
"""按 hd_id 聚合(账号池页 / stats/account 用)。"""
|
||||
out: dict[int, dict] = {}
|
||||
for ev in events:
|
||||
try:
|
||||
hd_id = int(ev.get("hd_id"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
_add(out.setdefault(hd_id, empty_counter()), ev)
|
||||
return out
|
||||
|
||||
|
||||
def aggregate_by_city(events: list[dict]) -> dict[str, dict]:
|
||||
"""按 target_city 聚合(城市页用)。"""
|
||||
out: dict[str, dict] = {}
|
||||
for ev in events:
|
||||
city = ev.get("target_city") or ev.get("bind_city")
|
||||
if not city:
|
||||
continue
|
||||
_add(out.setdefault(str(city), empty_counter()), ev)
|
||||
return out
|
||||
|
||||
|
||||
def timeline(start: date, end: date) -> list[dict]:
|
||||
"""按天时间线(概览趋势用),缺失日期给出 logs=False。"""
|
||||
items: list[dict] = []
|
||||
day = start
|
||||
while day <= end:
|
||||
events, meta = read_day(day)
|
||||
agg = aggregate(events)
|
||||
items.append(
|
||||
{
|
||||
"date": day.isoformat(),
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"logs": bool(meta.get("available")),
|
||||
}
|
||||
)
|
||||
day += timedelta(days=1)
|
||||
return items
|
||||
|
||||
|
||||
def available(day: date) -> bool:
|
||||
return any(p.is_file() for p in run_log_paths(day))
|
||||
|
||||
|
||||
# ── 审计(写操作)────────────────────────────────────────────────────────
|
||||
def write_audit(record: dict) -> bool:
|
||||
"""追加一行审计到 logs/audit.jsonl。任何异常都吞掉,返回是否写成功。"""
|
||||
try:
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with (LOG_DIR / AUDIT_FILE).open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
return True
|
||||
except Exception: # 审计失败不影响已提交的库变更
|
||||
logger.exception("写审计失败")
|
||||
return False
|
||||
|
||||
|
||||
def read_audit(limit: int = 50) -> list[dict]:
|
||||
"""读取审计文件末 limit 行(倒序)。"""
|
||||
path = LOG_DIR / AUDIT_FILE
|
||||
if not path.is_file():
|
||||
return []
|
||||
try:
|
||||
with path.open("r", encoding="utf-8", errors="replace") as f:
|
||||
lines = f.readlines()[-limit:]
|
||||
except OSError:
|
||||
return []
|
||||
out: list[dict] = []
|
||||
for line in reversed(lines):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(obj, dict):
|
||||
out.append(obj)
|
||||
return out
|
||||
|
||||
|
||||
def log_dir_info() -> dict:
|
||||
"""health 用:日志目录(可能多个)与可写性。"""
|
||||
import os
|
||||
|
||||
return {
|
||||
"log_dir": str(LOG_DIR),
|
||||
"log_dirs": [str(d) for d in LOG_DIRS],
|
||||
"log_exists": LOG_DIR.is_dir(),
|
||||
"log_writable": LOG_DIR.is_dir() and os.access(LOG_DIR, os.W_OK),
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""业务字典与脱敏工具(唯一实现处,前端不重复定义)。
|
||||
|
||||
- IS_OK_DICT : hotel_hd.is_ok 的状态字典(与 01 文档 3.2 一致)
|
||||
- CITY_GPS : 采集脚本 `酒店详情.py` 里的城市坐标表(合法城市的第二重约束)
|
||||
- 脱敏 : dfpid 只留后 8 位、代理只留 ip:port
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
# ── is_ok 状态字典 ──────────────────────────────────────────────────────
|
||||
# tone 供前端选色:ok=绿 / danger=红 / warn=橙 / muted=灰
|
||||
IS_OK_DICT: dict[str, dict] = {
|
||||
"NULL": {"text": "可用", "tone": "ok"},
|
||||
"403": {"text": "封禁/风控", "tone": "danger"},
|
||||
"401": {"text": "登录失效", "tone": "warn"},
|
||||
"418": {"text": "网络受限", "tone": "warn"},
|
||||
"0": {"text": "异常", "tone": "danger"},
|
||||
"6": {"text": "未知(6)", "tone": "muted"},
|
||||
"_other": {"text": "未知", "tone": "muted"},
|
||||
}
|
||||
|
||||
|
||||
def status_of(is_ok: int | None) -> tuple[str, str]:
|
||||
"""(文案, tone)。None → 可用。"""
|
||||
if is_ok is None:
|
||||
return IS_OK_DICT["NULL"]["text"], IS_OK_DICT["NULL"]["tone"]
|
||||
key = str(is_ok)
|
||||
item = IS_OK_DICT.get(key)
|
||||
if item:
|
||||
return item["text"], item["tone"]
|
||||
return f"{IS_OK_DICT['_other']['text']}({is_ok})", IS_OK_DICT["_other"]["tone"]
|
||||
|
||||
|
||||
# ── 城市坐标(与采集脚本 CITY_GPS 完全一致,共 40 城)──────────────────
|
||||
CITY_GPS: dict[str, tuple[str, str]] = {
|
||||
"苏州": ("31.3", "120.6"),
|
||||
"佛山": ("23.0", "113.1"),
|
||||
"长沙": ("28.2", "112.9"),
|
||||
"武汉": ("30.594940", "114.302634"),
|
||||
"杭州": ("30.231471", "120.018594"),
|
||||
"太原": ("37.9", "112.5"),
|
||||
"乌鲁木齐": ("43.8", "87.6"),
|
||||
"上海": ("30.948869", "121.303506"),
|
||||
"重庆": ("29.6", "106.5"),
|
||||
"成都": ("30.6", "104.1"),
|
||||
"南通": ("32.0", "120.9"),
|
||||
"深圳": ("22.545482", "114.055597"),
|
||||
"兰州": ("36.1", "103.8"),
|
||||
"海口": ("20.0", "110.3"),
|
||||
"济南": ("36.7", "117.0"),
|
||||
"南京": ("32.1", "118.8"),
|
||||
"郑州": ("34.7", "113.6"),
|
||||
"福州": ("26.1", "119.3"),
|
||||
"拉萨": ("29.7", "91.1"),
|
||||
"沈阳": ("41.8", "123.4"),
|
||||
"广州": ("23.437968", "113.554650"),
|
||||
"昆明": ("25.0", "102.7"),
|
||||
"北京": ("39.9", "116.4"),
|
||||
"天津": ("39.1", "117.2"),
|
||||
"长春": ("43.9", "125.3"),
|
||||
"西安": ("34.3", "108.9"),
|
||||
"哈尔滨": ("45.8", "126.5"),
|
||||
"贵阳": ("26.6", "106.7"),
|
||||
"银川": ("38.5", "106.2"),
|
||||
"西宁": ("36.616448", "101.775687"),
|
||||
"南昌": ("28.7", "115.9"),
|
||||
"呼和浩特": ("40.8", "111.7"),
|
||||
"石家庄": ("38.0", "114.5"),
|
||||
"南宁": ("22.8", "108.4"),
|
||||
"合肥": ("31.8", "117.2"),
|
||||
"青岛": ("36.1", "120.4"),
|
||||
"东莞": ("23.0", "113.8"),
|
||||
"厦门": ("24.5", "118.1"),
|
||||
"无锡": ("31.5", "120.3"),
|
||||
"大连": ("38.9", "121.6"),
|
||||
}
|
||||
|
||||
|
||||
def legal_cities(proxy_cities: list[str] | set[str]) -> list[str]:
|
||||
"""合法城市白名单 = 代理池城市 ∩ CITY_GPS。
|
||||
|
||||
南通有坐标但没有代理 IP,因此天然被排除;改成白名单外的城市会让采集脚本
|
||||
`run_one()` 在补 IP 分支抛 AttributeError。
|
||||
"""
|
||||
return sorted({c for c in proxy_cities if c} & CITY_GPS.keys())
|
||||
|
||||
|
||||
# ── 脱敏 ────────────────────────────────────────────────────────────────
|
||||
_DFPID_TAIL = 8
|
||||
# 实测 hotel_hd.dfpid 共 348 行全部带中文后缀(导入时把 title 拼在了后面,
|
||||
# 如 'u94x6…uw71xu美团酒店详情'),脱敏前必须先剔掉中文部分
|
||||
_CN_SUFFIX = re.compile(r"[\u4e00-\u9fff].*$")
|
||||
|
||||
|
||||
def mask_dfpid(dfpid: str | None) -> str | None:
|
||||
"""dfpid → `…` + 后 8 位(先剔除尾部中文标题);完整值只在后端使用。"""
|
||||
if not dfpid:
|
||||
return None
|
||||
s = _CN_SUFFIX.sub("", str(dfpid)).strip()
|
||||
if not s:
|
||||
return None
|
||||
return "…" + s[-_DFPID_TAIL:] if len(s) > _DFPID_TAIL else "…" + s
|
||||
|
||||
|
||||
_PROX_IP_PORT = re.compile(r"@([0-9a-zA-Z.\-]+):(\d+)")
|
||||
|
||||
|
||||
def extract_prox_ip(prox: str | None) -> str | None:
|
||||
"""从代理 JSON 抽 `ip:port`,账号密码一律丢弃。"""
|
||||
if not prox:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(prox) if isinstance(prox, str) else prox
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
for value in data.values():
|
||||
if not isinstance(value, str):
|
||||
continue
|
||||
m = _PROX_IP_PORT.search(value)
|
||||
if m:
|
||||
return f"{m.group(1)}:{m.group(2)}"
|
||||
return None
|
||||
@@ -0,0 +1,362 @@
|
||||
"""数据查询层:hotel_hd(账号池)+ hotel_task / hotel_json(记录)。
|
||||
|
||||
说明:
|
||||
- hotel_hd 只有约 350 行,因此账号池相关的筛选/排序/分页在内存里做,
|
||||
这样能一次 merge 今日日志跑量,避免 N+1;
|
||||
- hotel_task / hotel_json 是大表(7k / 10k+ 行),一律服务端 SQL 分页;
|
||||
- hotel_json 列表绝不返回 json_data(单条 130~440KB),只给 LENGTH()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..config import HOTEL_TITLE_LIKE
|
||||
from ..database import headers_engine, main_engine
|
||||
from .hotel_meta import extract_prox_ip, mask_dfpid, status_of
|
||||
|
||||
# ── 账号池 ──────────────────────────────────────────────────────────────
|
||||
_POOL_SQL = text(
|
||||
"""
|
||||
SELECT COUNT(*) AS total,
|
||||
SUM(is_ok IS NULL) AS available,
|
||||
SUM(is_ok = 403) AS s403,
|
||||
SUM(is_ok = 401) AS s401,
|
||||
SUM(is_ok = 418) AS s418,
|
||||
SUM(is_ok = 0) AS s0,
|
||||
SUM(is_ok = 6) AS s6,
|
||||
SUM(is_ok IS NOT NULL AND is_ok NOT IN (403, 401, 418, 0, 6)) AS other
|
||||
FROM hotel_hd
|
||||
WHERE title LIKE :pat
|
||||
"""
|
||||
)
|
||||
|
||||
_ACCOUNTS_SQL = text(
|
||||
"""
|
||||
SELECT id, dfpid, ip, channel, title, is_ok, req_count, current_count,
|
||||
prox, city, mt_traceid, created_at, updated_at
|
||||
FROM hotel_hd
|
||||
WHERE title LIKE :pat
|
||||
"""
|
||||
)
|
||||
|
||||
_STATUS_KEYS = {"403", "401", "418", "0", "6"}
|
||||
|
||||
|
||||
async def pool_stats() -> dict:
|
||||
"""池子健康度(口径与 01 文档 3.2/3.4 一致)。"""
|
||||
async with headers_engine.connect() as conn:
|
||||
row = (await conn.execute(_POOL_SQL, {"pat": HOTEL_TITLE_LIKE})).first()
|
||||
data = {k: int(v or 0) for k, v in dict(row._mapping).items()} if row else {}
|
||||
total = data.get("total", 0)
|
||||
data["others_all"] = data.get("s418", 0) + data.get("s0", 0) + data.get("s6", 0) + data.get("other", 0)
|
||||
data["available_rate"] = round(data.get("available", 0) / total * 100, 1) if total else None
|
||||
return data
|
||||
|
||||
|
||||
def _match_status(is_ok, wanted: set[str]) -> bool:
|
||||
key = "NULL" if is_ok is None else str(is_ok)
|
||||
if key in wanted:
|
||||
return True
|
||||
if "OTHER" in wanted and is_ok is not None and key not in _STATUS_KEYS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fmt_dt(value) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(value)
|
||||
|
||||
|
||||
def _decorate_account(row: dict, today: dict | None) -> dict:
|
||||
is_ok = row.get("is_ok")
|
||||
text_, tone = status_of(is_ok)
|
||||
prox = row.get("prox")
|
||||
return {
|
||||
"id": row["id"],
|
||||
# ── hotel_hd 原始列(页面 1 直接展示)──────────────────────────
|
||||
"is_ok": is_ok,
|
||||
"req_count": int(row.get("req_count") or 0),
|
||||
"current_count": int(row.get("current_count") or 0),
|
||||
"prox_raw": prox, # 原始代理 JSON(含账号密码,按用户要求原样展示)
|
||||
"city": row.get("city"),
|
||||
"mt_traceid": row.get("mt_traceid"),
|
||||
"created_at": _fmt_dt(row.get("created_at")),
|
||||
"updated_at": _fmt_dt(row.get("updated_at")),
|
||||
# ── 辅助字段(状态文案 / 脱敏 / 今日跑量)──────────────────────
|
||||
"dfpid_tail": mask_dfpid(row.get("dfpid")),
|
||||
"has_prox": bool(prox),
|
||||
"prox_ip": extract_prox_ip(prox),
|
||||
"status_text": text_,
|
||||
"status_tone": tone,
|
||||
"today": {
|
||||
"fetch_task": (today or {}).get("fetch_task", 0),
|
||||
"upload_ok": (today or {}).get("upload_ok", 0),
|
||||
"upload_fail": (today or {}).get("upload_fail", 0),
|
||||
"fetch_empty": (today or {}).get("fetch_empty", 0),
|
||||
},
|
||||
"ip": row.get("ip"),
|
||||
"channel": row.get("channel"),
|
||||
}
|
||||
|
||||
|
||||
async def all_accounts_raw() -> list[dict]:
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(_ACCOUNTS_SQL, {"pat": HOTEL_TITLE_LIKE})).fetchall()
|
||||
return [dict(r._mapping) for r in rows]
|
||||
|
||||
|
||||
async def account_rows(
|
||||
*,
|
||||
today_agg: dict[int, dict],
|
||||
city: str | None = None,
|
||||
status: list[str] | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
sort: str = "id",
|
||||
order: str = "desc",
|
||||
) -> tuple[list[dict], int]:
|
||||
"""账号池筛选/排序/分页(内存态,350 行级别)。"""
|
||||
rows = await all_accounts_raw()
|
||||
wanted = {s.upper() for s in (status or [])}
|
||||
if city:
|
||||
rows = [r for r in rows if (r.get("city") or "") == city]
|
||||
if wanted:
|
||||
rows = [r for r in rows if _match_status(r.get("is_ok"), wanted)]
|
||||
if keyword:
|
||||
kw = keyword.strip().lower()
|
||||
rows = [r for r in rows if kw in str(r.get("dfpid") or "").lower()]
|
||||
|
||||
items = [_decorate_account(r, today_agg.get(r["id"])) for r in rows]
|
||||
|
||||
key_map = {
|
||||
"id": lambda x: x["id"],
|
||||
"today_fetch_task": lambda x: x["today"]["fetch_task"],
|
||||
"updated_at": lambda x: x["updated_at"] or "",
|
||||
"req_count": lambda x: x["req_count"],
|
||||
"current_count": lambda x: x["current_count"],
|
||||
}
|
||||
key = key_map.get(sort, key_map["id"])
|
||||
items.sort(key=key, reverse=(order.lower() != "asc"))
|
||||
|
||||
total = len(items)
|
||||
start = max(page - 1, 0) * size
|
||||
return items[start : start + size], total
|
||||
|
||||
|
||||
async def get_account(hd_id: int) -> dict | None:
|
||||
sql = text(
|
||||
"SELECT id, dfpid, city, prox, is_ok, req_count, current_count "
|
||||
"FROM hotel_hd WHERE id = :id AND title LIKE :pat"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
row = (await conn.execute(sql, {"id": hd_id, "pat": HOTEL_TITLE_LIKE})).first()
|
||||
return dict(row._mapping) if row else None
|
||||
|
||||
|
||||
async def city_account_counts() -> dict[str, int]:
|
||||
sql = text(
|
||||
"SELECT city, COUNT(*) AS n FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND city IS NOT NULL AND city <> '' GROUP BY city"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE})).fetchall()
|
||||
return {r[0]: int(r[1]) for r in rows}
|
||||
|
||||
|
||||
async def proxy_city_ips() -> dict[str, int]:
|
||||
"""每城可用代理 IP 数(proxs_list,channel = 到期日,非空即有效)。"""
|
||||
sql = text(
|
||||
"SELECT city, COUNT(*) AS ips FROM project_proxy.proxs_list "
|
||||
"WHERE channel IS NOT NULL AND channel <> '' AND city IS NOT NULL "
|
||||
"GROUP BY city"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql)).fetchall()
|
||||
return {r[0]: int(r[1]) for r in rows}
|
||||
|
||||
|
||||
async def available_accounts() -> list[dict]:
|
||||
"""可用账号(is_ok IS NULL),带 current_count —— 用于算"手上包还剩多少产能"。"""
|
||||
sql = text(
|
||||
"SELECT id, city, current_count FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND is_ok IS NULL ORDER BY current_count DESC, id DESC"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE})).fetchall()
|
||||
return [
|
||||
{"id": r[0], "city": r[1], "current_count": int(r[2] or 0)} for r in rows
|
||||
]
|
||||
|
||||
|
||||
async def stale_accounts(hours: int = 24, limit: int = 100) -> list[dict]:
|
||||
"""可用(is_ok IS NULL)但超过 N 小时没活动的账号。"""
|
||||
sql = text(
|
||||
"SELECT id, dfpid, city, updated_at, "
|
||||
" TIMESTAMPDIFF(MINUTE, updated_at, NOW()) AS idle_minutes "
|
||||
"FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND is_ok IS NULL AND updated_at < NOW() - INTERVAL :h HOUR "
|
||||
"ORDER BY updated_at ASC LIMIT :lim"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE, "h": hours, "lim": limit})).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
d = dict(r._mapping)
|
||||
out.append(
|
||||
{
|
||||
"hd_id": d["id"],
|
||||
"dfpid_tail": mask_dfpid(d.get("dfpid")),
|
||||
"city": d.get("city"),
|
||||
"updated_at": d["updated_at"].strftime("%Y-%m-%d %H:%M:%S") if d.get("updated_at") else None,
|
||||
"hours": round((d.get("idle_minutes") or 0) / 60, 1),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
async def blocked_accounts(limit: int = 500) -> list[dict]:
|
||||
"""所有非 NULL 状态(封禁清单)。"""
|
||||
sql = text(
|
||||
"SELECT id, dfpid, city, is_ok, updated_at FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND is_ok IS NOT NULL "
|
||||
"ORDER BY is_ok, updated_at DESC LIMIT :lim"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE, "lim": limit})).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
d = dict(r._mapping)
|
||||
text_, tone = status_of(d.get("is_ok"))
|
||||
out.append(
|
||||
{
|
||||
"hd_id": d["id"],
|
||||
"dfpid_tail": mask_dfpid(d.get("dfpid")),
|
||||
"city": d.get("city"),
|
||||
"is_ok": d["is_ok"],
|
||||
"status_text": text_,
|
||||
"status_tone": tone,
|
||||
"updated_at": d["updated_at"].strftime("%Y-%m-%d %H:%M:%S") if d.get("updated_at") else None,
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
# ── 任务记录 ─────────────────────────────────────────────────────────────
|
||||
_TASK_COLS = (
|
||||
"id, hotel_id, city_id, hotel_name, city_name, check_in_date, check_out_date, "
|
||||
"unique_id, hotel_star, selected_city, area_type, area_name, created_at, updated_at"
|
||||
)
|
||||
|
||||
|
||||
async def tasks_page(
|
||||
*,
|
||||
start: date,
|
||||
end: date,
|
||||
city: str | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
) -> tuple[list[dict], int]:
|
||||
where = "created_at >= :start AND created_at < :end_ex"
|
||||
params: dict = {"start": start, "end_ex": end + timedelta(days=1)}
|
||||
if city:
|
||||
where += " AND city_name = :city"
|
||||
params["city"] = city if city.endswith("市") else f"{city}市"
|
||||
if keyword:
|
||||
where += " AND (hotel_name LIKE :kw OR unique_id LIKE :kw_pre)"
|
||||
params["kw"] = f"%{keyword}%"
|
||||
params["kw_pre"] = f"{keyword}%"
|
||||
|
||||
count_sql = text(f"SELECT COUNT(*) FROM hotel_task WHERE {where}")
|
||||
list_sql = text(
|
||||
f"SELECT {_TASK_COLS} FROM hotel_task WHERE {where} "
|
||||
"ORDER BY created_at DESC, id DESC LIMIT :size OFFSET :offset"
|
||||
)
|
||||
async with main_engine.connect() as conn:
|
||||
total = int((await conn.execute(count_sql, params)).scalar() or 0)
|
||||
rows = (
|
||||
await conn.execute(
|
||||
list_sql, {**params, "size": size, "offset": max(page - 1, 0) * size}
|
||||
)
|
||||
).fetchall()
|
||||
return [_json_row(r) for r in rows], total
|
||||
|
||||
|
||||
# ── 采集记录 ─────────────────────────────────────────────────────────────
|
||||
# ⚠ 不要 SELECT LENGTH(json_data):实测远程库上单次 38s(longtext 溢出页需跨网读取),
|
||||
# 列表只取元数据;json_size 在详情接口里用 Python len() 算。
|
||||
_RECORD_COLS = (
|
||||
"id, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date, create_at"
|
||||
)
|
||||
|
||||
|
||||
async def records_page(
|
||||
*,
|
||||
start: date,
|
||||
end: date,
|
||||
city: str | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
) -> tuple[list[dict], int]:
|
||||
where = "create_at >= :start AND create_at < :end_ex"
|
||||
params: dict = {"start": start, "end_ex": end + timedelta(days=1)}
|
||||
if city:
|
||||
where += " AND city_name = :city"
|
||||
params["city"] = city if city.endswith("市") else f"{city}市"
|
||||
if keyword:
|
||||
where += " AND (hotel_name LIKE :kw OR poi_id LIKE :kw_pre)"
|
||||
params["kw"] = f"%{keyword}%"
|
||||
params["kw_pre"] = f"{keyword}%"
|
||||
|
||||
count_sql = text(f"SELECT COUNT(*) FROM hotel_json WHERE {where}")
|
||||
list_sql = text(
|
||||
f"SELECT {_RECORD_COLS} FROM hotel_json WHERE {where} "
|
||||
"ORDER BY create_at DESC, id DESC LIMIT :size OFFSET :offset"
|
||||
)
|
||||
async with main_engine.connect() as conn:
|
||||
total = int((await conn.execute(count_sql, params)).scalar() or 0)
|
||||
rows = (
|
||||
await conn.execute(
|
||||
list_sql, {**params, "size": size, "offset": max(page - 1, 0) * size}
|
||||
)
|
||||
).fetchall()
|
||||
return [_json_row(r) for r in rows], total
|
||||
|
||||
|
||||
async def record_by_id(rec_id: int) -> dict | None:
|
||||
sql = text(
|
||||
"SELECT id, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date, "
|
||||
"create_at, json_data "
|
||||
"FROM hotel_json WHERE id = :id"
|
||||
)
|
||||
async with main_engine.connect() as conn:
|
||||
row = (await conn.execute(sql, {"id": rec_id})).first()
|
||||
return dict(row._mapping) if row else None
|
||||
|
||||
|
||||
async def count_today(table: str, day: date) -> int:
|
||||
"""某表某天的行数(hotel_task 用 created_at,hotel_json 用 create_at)。"""
|
||||
col = "created_at" if table == "hotel_task" else "create_at"
|
||||
sql = text(f"SELECT COUNT(*) FROM {table} WHERE {col} >= :s AND {col} < :e")
|
||||
async with main_engine.connect() as conn:
|
||||
return int((await conn.execute(sql, {"s": day, "e": day + timedelta(days=1)})).scalar() or 0)
|
||||
|
||||
|
||||
def _json_row(row) -> dict:
|
||||
out = {}
|
||||
for k, v in dict(row._mapping).items():
|
||||
if isinstance(v, datetime):
|
||||
out[k] = v.strftime("%Y-%m-%d %H:%M:%S")
|
||||
elif isinstance(v, date):
|
||||
out[k] = v.isoformat()
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
@@ -0,0 +1,139 @@
|
||||
"""hotel_hd 写操作:改绑定城市(同时清空 prox)与单条重置 is_ok。
|
||||
|
||||
约束(01 文档 FR-7):
|
||||
- 只允许更新 city / prox / is_ok 三列;
|
||||
- 单事务 + SELECT ... FOR UPDATE,数据库失败整体回滚且不写审计;
|
||||
- 城市必须在合法白名单(代理池 ∩ CITY_GPS)内,且该城至少有 1 个可用代理 IP;
|
||||
- 审计在事务提交后追加到 logs/audit.jsonl,写失败不影响已提交的库变更(响应里 audit_ok=false)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..config import HOTEL_TITLE_LIKE
|
||||
from ..database import headers_engine
|
||||
from . import hotel_logs
|
||||
from .hotel_meta import extract_prox_ip, mask_dfpid
|
||||
|
||||
|
||||
class WriteError(Exception):
|
||||
"""业务校验失败,router 层转成 HTTP 错误。"""
|
||||
|
||||
def __init__(self, code: int, msg: str, status: int = 400):
|
||||
super().__init__(msg)
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
self.status = status
|
||||
|
||||
|
||||
_SELECT_ONE = text(
|
||||
"SELECT id, dfpid, city, prox, is_ok, req_count, current_count FROM hotel_hd "
|
||||
"WHERE id = :id AND title LIKE :pat FOR UPDATE"
|
||||
)
|
||||
|
||||
|
||||
async def change_city(
|
||||
hd_id: int,
|
||||
new_city: str,
|
||||
*,
|
||||
legal_cities: list[str],
|
||||
proxy_ips: dict[str, int],
|
||||
operator: str = "local",
|
||||
) -> dict:
|
||||
new_city = (new_city or "").strip()
|
||||
if not new_city:
|
||||
raise WriteError(1001, "城市不能为空")
|
||||
if new_city not in set(legal_cities):
|
||||
raise WriteError(1002, f"城市「{new_city}」不在可用代理城市清单内")
|
||||
if proxy_ips.get(new_city, 0) <= 0:
|
||||
raise WriteError(1003, f"城市「{new_city}」当前没有可用代理,请先在代理池补充")
|
||||
|
||||
async with headers_engine.begin() as conn:
|
||||
row = (await conn.execute(_SELECT_ONE, {"id": hd_id, "pat": HOTEL_TITLE_LIKE})).first()
|
||||
if not row:
|
||||
raise WriteError(1005, f"账号 #{hd_id} 不存在", status=404)
|
||||
old = dict(row._mapping)
|
||||
# 同城判断放在 is_ok 之前:用户点了同一个城市,提示「无需修改」比「状态不对」更贴合意图。
|
||||
if (old.get("city") or "") == new_city:
|
||||
raise WriteError(1004, "新旧城市相同,无需修改")
|
||||
# 允许操作的两种情况:
|
||||
# ① is_ok=0(异常包) → 改城市,复活它
|
||||
# ② is_ok=NULL 且 city 为空(全新包)→ 添加城市,让它能跑起来
|
||||
# 403/401/418 是 headers 失效或风控,换城市没用;已绑城市的可用包也不该乱动。
|
||||
is_new_package = old.get("is_ok") is None and not (old.get("city") or "").strip()
|
||||
if old.get("is_ok") != 0 and not is_new_package:
|
||||
current = "NULL" if old.get("is_ok") is None else f"{old.get('is_ok')}"
|
||||
raise WriteError(
|
||||
1006,
|
||||
f"只有 is_ok=0(异常包)或 is_ok=NULL 且未绑城市(新包)才能改/加城市,"
|
||||
f"当前 is_ok={current} city={old.get('city') or 'NULL'}",
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
text("UPDATE hotel_hd SET city = :city, prox = NULL, is_ok = NULL WHERE id = :id"),
|
||||
{"city": new_city, "id": hd_id},
|
||||
)
|
||||
|
||||
audit_ok = hotel_logs.write_audit(
|
||||
{
|
||||
"ts": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"action": "set_city" if is_new_package else "change_city",
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(old.get("dfpid")),
|
||||
"old_city": old.get("city"),
|
||||
"new_city": new_city,
|
||||
"old_prox_ip": extract_prox_ip(old.get("prox")),
|
||||
"new_prox_ip": None,
|
||||
"old_is_ok": old.get("is_ok"),
|
||||
"new_is_ok": None,
|
||||
"operator": operator,
|
||||
"result": "ok",
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"id": hd_id,
|
||||
"old_city": old.get("city"),
|
||||
"new_city": new_city,
|
||||
"mode": "add" if is_new_package else "change",
|
||||
"prox_cleared": True,
|
||||
"is_ok_reset": True,
|
||||
"proxy_ips_in_city": proxy_ips.get(new_city, 0),
|
||||
"audit_ok": audit_ok,
|
||||
}
|
||||
|
||||
|
||||
async def reset_is_ok(hd_id: int, *, operator: str = "local") -> dict:
|
||||
async with headers_engine.begin() as conn:
|
||||
row = (await conn.execute(_SELECT_ONE, {"id": hd_id, "pat": HOTEL_TITLE_LIKE})).first()
|
||||
if not row:
|
||||
raise WriteError(1005, f"账号 #{hd_id} 不存在", status=404)
|
||||
old = dict(row._mapping)
|
||||
if old.get("is_ok") is None:
|
||||
raise WriteError(1004, "该账号已是可用状态,无需重置")
|
||||
|
||||
await conn.execute(
|
||||
text("UPDATE hotel_hd SET is_ok = NULL WHERE id = :id"), {"id": hd_id}
|
||||
)
|
||||
|
||||
audit_ok = hotel_logs.write_audit(
|
||||
{
|
||||
"ts": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"action": "reset_is_ok",
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(old.get("dfpid")),
|
||||
"old_city": old.get("city"),
|
||||
"new_city": old.get("city"),
|
||||
"old_prox_ip": extract_prox_ip(old.get("prox")),
|
||||
"new_prox_ip": extract_prox_ip(old.get("prox")),
|
||||
"old_is_ok": old.get("is_ok"),
|
||||
"new_is_ok": None,
|
||||
"operator": operator,
|
||||
"result": "ok",
|
||||
}
|
||||
)
|
||||
|
||||
return {"id": hd_id, "old_is_ok": old.get("is_ok"), "new_is_ok": None, "audit_ok": audit_ok}
|
||||
@@ -0,0 +1,128 @@
|
||||
"""任务平台 OpenAPI 只读代理。
|
||||
|
||||
只允许三个只读接口:
|
||||
/getStats 按日期(+可选城市)拿成功/拒收/剩余
|
||||
/realtimeCityList 实时城市列表
|
||||
/realtimeCheckInOutDateList 可领取的入离日期
|
||||
⛔ 永不调用 /getTask、/uploadTaskDatagram(会消耗真实任务)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
|
||||
import requests
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..config import (
|
||||
PLATFORM_BASE,
|
||||
PLATFORM_CACHE_SECONDS,
|
||||
PLATFORM_PWD,
|
||||
PLATFORM_TIMEOUT,
|
||||
PLATFORM_USER,
|
||||
PLATFORM_VENDOR,
|
||||
)
|
||||
|
||||
# 直连(绕开本机 VPN),与采集脚本一致
|
||||
_DIRECT = {"http": "", "https": ""}
|
||||
_cache: dict[tuple, tuple[float, dict]] = {}
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
token = base64.b64encode(f"{PLATFORM_USER}:{PLATFORM_PWD}".encode()).decode()
|
||||
return {"Authorization": f"Basic {token}"}
|
||||
|
||||
|
||||
def _get(path: str, params: dict) -> dict:
|
||||
resp = requests.get(
|
||||
PLATFORM_BASE + path,
|
||||
headers=_headers(),
|
||||
params=params,
|
||||
timeout=PLATFORM_TIMEOUT,
|
||||
proxies=_DIRECT,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _cached(key: tuple, producer, ttl: int) -> dict:
|
||||
now = time.time()
|
||||
with _lock:
|
||||
hit = _cache.get(key)
|
||||
if hit and now - hit[0] < ttl:
|
||||
return hit[1]
|
||||
value = producer()
|
||||
with _lock:
|
||||
_cache[key] = (now, value)
|
||||
return value
|
||||
|
||||
|
||||
def get_stats_sync(day: date, city: str | None = None) -> dict:
|
||||
"""平台侧统计(单一城市或不传城市=全平台)。
|
||||
|
||||
历史日期(< 今天)结果不会再变,缓存 30 分钟;当天缓存 60 秒。
|
||||
"""
|
||||
ttl = PLATFORM_CACHE_SECONDS if day >= date.today() else 1800
|
||||
|
||||
def produce() -> dict:
|
||||
params = {"date": day.isoformat(), "vendorName": PLATFORM_VENDOR}
|
||||
if city:
|
||||
params["clientId"] = city
|
||||
try:
|
||||
body = _get("/getStats", params)
|
||||
data = body.get("data") or {}
|
||||
return {
|
||||
"ok": True,
|
||||
"date": day.isoformat(),
|
||||
"city": city,
|
||||
"success": data.get("success"),
|
||||
"reject": data.get("reject"),
|
||||
"remain": data.get("remain"),
|
||||
"timeout": data.get("timeout"),
|
||||
"cancel": data.get("cancel"),
|
||||
"error": None,
|
||||
}
|
||||
except Exception as e: # noqa: BLE001 上游失败不阻塞页面
|
||||
return {
|
||||
"ok": False,
|
||||
"date": day.isoformat(),
|
||||
"city": city,
|
||||
"error": f"{type(e).__name__}: {e}"[:200],
|
||||
}
|
||||
|
||||
return _cached(("getStats", day.isoformat(), city or ""), produce, ttl)
|
||||
|
||||
|
||||
async def get_stats(day: date, city: str | None = None) -> dict:
|
||||
return await run_in_threadpool(get_stats_sync, day, city)
|
||||
|
||||
|
||||
def city_stats_sync(day: date, cities: list[str], concurrency: int = 5) -> list[dict]:
|
||||
"""按城市批量取平台统计(串行限流,避免打爆上游)。"""
|
||||
out: list[dict] = []
|
||||
for city in cities:
|
||||
out.append(get_stats_sync(day, city))
|
||||
return out
|
||||
|
||||
|
||||
async def city_stats(day: date, cities: list[str]) -> list[dict]:
|
||||
return await run_in_threadpool(city_stats_sync, day, cities)
|
||||
|
||||
|
||||
def dates_sync() -> list[dict]:
|
||||
def produce() -> dict:
|
||||
try:
|
||||
body = _get("/realtimeCheckInOutDateList", {"vendorName": PLATFORM_VENDOR})
|
||||
return {"ok": True, "items": body.get("data") or []}
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {"ok": False, "items": [], "error": f"{type(e).__name__}: {e}"[:200]}
|
||||
|
||||
return _cached(("dates",), produce, PLATFORM_CACHE_SECONDS).get("items", [])
|
||||
|
||||
|
||||
async def available_dates() -> list[dict]:
|
||||
return await run_in_threadpool(dates_sync)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""hotel_json.json_data 解析:把采集响应里的房型/价格抽成结构化列表。
|
||||
|
||||
支持结构:
|
||||
- prepayList(当前生产数据,`roomGoodsList.data[].goodsList[]`)—— 完整解析
|
||||
- dayRoomShelfModel(历史 shelf 响应)—— 尽力而为,失败则 parse_ok=False
|
||||
价格单位:原始为「分」,统一转「元」(保留 2 位)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
RAW_PREVIEW_LIMIT = 100 * 1024 # 100KB
|
||||
MAX_ROOMS = 200
|
||||
|
||||
|
||||
def _yuan(value) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return round(float(value) / 100.0, 2)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _iter_goods(doc: dict):
|
||||
container = doc.get("roomGoodsList") or {}
|
||||
if isinstance(container, dict):
|
||||
blocks = container.get("data") or []
|
||||
elif isinstance(container, list):
|
||||
blocks = container
|
||||
else:
|
||||
blocks = []
|
||||
for block in blocks:
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
for goods in block.get("goodsList") or []:
|
||||
if isinstance(goods, dict):
|
||||
yield goods
|
||||
|
||||
|
||||
def _room_from_goods(goods: dict) -> dict:
|
||||
price_info = goods.get("priceInfo") or {}
|
||||
room_model = goods.get("goodsRoomModel") or {}
|
||||
payment = (goods.get("paymentTypeTips") or {}).get("tips")
|
||||
price = _yuan(price_info.get("averagePrice"))
|
||||
origin = _yuan(price_info.get("originalPrice"))
|
||||
inventory = goods.get("inventory")
|
||||
if inventory is None:
|
||||
inventory = goods.get("invRemain")
|
||||
return {
|
||||
"room_name": room_model.get("roomName") or goods.get("realRoomName") or "",
|
||||
"goods_name": goods.get("goodsName") or "",
|
||||
"price": price,
|
||||
"origin_price": origin,
|
||||
"inventory": int(inventory) if isinstance(inventory, (int, float)) else None,
|
||||
"tag": goods.get("tagName") or None,
|
||||
"payment": payment or None,
|
||||
"goods_id": goods.get("goodsId"),
|
||||
"promotion": price_info.get("promotionSubTitle") or None,
|
||||
}
|
||||
|
||||
|
||||
def parse_record(json_data) -> dict:
|
||||
"""解析一条 json_data,返回 {parse_ok, structure, rooms, min_price, error}。"""
|
||||
if isinstance(json_data, (bytes, bytearray)):
|
||||
try:
|
||||
json_data = json_data.decode("utf-8", errors="replace")
|
||||
except Exception: # noqa: BLE001
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "编码解析失败"}
|
||||
|
||||
if isinstance(json_data, str):
|
||||
try:
|
||||
doc = json.loads(json_data)
|
||||
except ValueError:
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "JSON 解析失败"}
|
||||
elif isinstance(json_data, dict):
|
||||
doc = json_data
|
||||
else:
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "未知数据类型"}
|
||||
|
||||
if not isinstance(doc, dict):
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "顶层不是对象"}
|
||||
|
||||
# ① prepayList:roomGoodsList
|
||||
if "roomGoodsList" in doc:
|
||||
rooms = []
|
||||
for goods in _iter_goods(doc):
|
||||
room = _room_from_goods(goods)
|
||||
if room["price"] is None and not room["room_name"]:
|
||||
continue
|
||||
rooms.append(room)
|
||||
if len(rooms) >= MAX_ROOMS:
|
||||
break
|
||||
rooms.sort(key=lambda r: (r["price"] is None, r["price"] if r["price"] is not None else 0))
|
||||
prices = [r["price"] for r in rooms if r["price"] is not None]
|
||||
return {
|
||||
"parse_ok": bool(rooms),
|
||||
"structure": "prepayList",
|
||||
"rooms": rooms,
|
||||
"min_price": min(prices) if prices else None,
|
||||
"error": None if rooms else "roomGoodsList 为空",
|
||||
}
|
||||
|
||||
# ② 历史 shelf 响应:结构过于嵌套,仅识别,不做结构化
|
||||
if "dayRoomShelfModel" in doc or (doc.get("results") and "dayRoomShelfModel" in json.dumps(doc)[:5000]):
|
||||
return {
|
||||
"parse_ok": False,
|
||||
"structure": "dayRoomShelfModel",
|
||||
"rooms": [],
|
||||
"min_price": None,
|
||||
"error": "历史 shelf 结构暂不支持结构化解析,请查看原始 JSON",
|
||||
}
|
||||
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "未知响应结构"}
|
||||
|
||||
|
||||
def raw_preview(json_data, limit: int = RAW_PREVIEW_LIMIT) -> tuple[str, bool]:
|
||||
"""返回 (预览文本, 是否被截断)。"""
|
||||
if isinstance(json_data, (bytes, bytearray)):
|
||||
json_data = json_data.decode("utf-8", errors="replace")
|
||||
text = json_data if isinstance(json_data, str) else json.dumps(json_data, ensure_ascii=False)
|
||||
if len(text) <= limit:
|
||||
return text, False
|
||||
return text[:limit], True
|
||||
@@ -0,0 +1,8 @@
|
||||
fastapi>=0.115
|
||||
uvicorn[standard]>=0.30
|
||||
sqlalchemy[asyncio]>=2.0.36
|
||||
aiomysql>=0.2.0
|
||||
pydantic>=2.8
|
||||
python-dotenv>=1.0
|
||||
pymysql>=1.1
|
||||
requests>=2.31
|
||||
@@ -0,0 +1,205 @@
|
||||
"""冒烟检查:按区块验证后端接口。
|
||||
|
||||
用法(后端已在运行时):
|
||||
python scripts/smoke.py # 全部区块
|
||||
python scripts/smoke.py --only overview,trend # 只测指定区块
|
||||
python scripts/smoke.py --base http://127.0.0.1:8096
|
||||
退出码 0 = 全部通过,1 = 有失败项。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
FAILS: list[str] = []
|
||||
CHECKS: dict = {}
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def get(base: str, path: str, timeout: int = 40) -> dict:
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def block(name: str):
|
||||
def deco(fn):
|
||||
CHECKS[name] = fn
|
||||
return fn
|
||||
|
||||
return deco
|
||||
|
||||
|
||||
@block("health")
|
||||
def check_health(base: str) -> None:
|
||||
h = get(base, "/api/health")["data"]
|
||||
print(f" db_main={h.get('db_main')} db_headers={h.get('db_headers')} log_writable={h.get('log_writable')}")
|
||||
check(h.get("db_main") == "up", "主库连通")
|
||||
check(h.get("db_headers") == "up", "抓包库连通")
|
||||
check(bool(h.get("log_writable")), "日志目录可写")
|
||||
|
||||
|
||||
@block("meta")
|
||||
def check_meta(base: str) -> None:
|
||||
m = get(base, "/api/hotel/meta")["data"]
|
||||
legal = m.get("legal_cities", [])
|
||||
print(f" legal_cities={len(legal)} cities={len(m.get('cities', []))}")
|
||||
check(bool(legal), "合法城市白名单非空")
|
||||
check("南通" not in legal, "南通不在白名单")
|
||||
check(bool(m.get("is_ok_dict")), "is_ok 字典存在")
|
||||
|
||||
|
||||
@block("overview")
|
||||
def check_overview(base: str) -> None:
|
||||
o = get(base, "/api/hotel/overview")["data"]
|
||||
pool = o.get("pool", {})
|
||||
print(f" pool: total={pool.get('total')} available={pool.get('available')} "
|
||||
f"403={pool.get('s403')} 401={pool.get('s401')} others={pool.get('others_all')} "
|
||||
f"rate={pool.get('available_rate')}")
|
||||
print(f" today: {json.dumps(o.get('today'), ensure_ascii=False)}")
|
||||
print(f" logs_available={o.get('logs_available')} db_today={o.get('db_today')}")
|
||||
plat = o.get("platform") or {}
|
||||
print(f" platform: ok={plat.get('ok')} success={plat.get('success')} reject={plat.get('reject')} "
|
||||
f"remain={plat.get('remain')}" + ("" if plat.get("ok") else f" error={plat.get('error')}"))
|
||||
check(pool.get("total", 0) > 0, "账号总数 > 0", str(pool.get("total")))
|
||||
summed = (pool.get("available", 0) + pool.get("s403", 0) + pool.get("s401", 0)
|
||||
+ pool.get("others_all", 0))
|
||||
check(summed == pool.get("total", -1), "健康度分项之和 = 总数", f"{summed} vs {pool.get('total')}")
|
||||
check("success_rate" in o.get("today", {}), "today.success_rate 存在")
|
||||
|
||||
|
||||
@block("trend")
|
||||
def check_trend(base: str) -> None:
|
||||
t = get(base, "/api/hotel/trend?days=7")["data"]
|
||||
items = t.get("items", [])
|
||||
print(f" days={len(items)} last={json.dumps(items[-1], ensure_ascii=False) if items else None}")
|
||||
check(len(items) == 7, "返回 7 个点", str(len(items)))
|
||||
|
||||
|
||||
@block("accounts")
|
||||
def check_accounts(base: str) -> None:
|
||||
a = get(base, "/api/hotel/accounts?page=1&size=5&sort=id&order=desc")["data"]
|
||||
items = a.get("items", [])
|
||||
print(f" total={a.get('total')} size={len(items)}")
|
||||
if items:
|
||||
print(" sample:", json.dumps(items[0], ensure_ascii=False))
|
||||
check(a.get("total", 0) > 0, "账号池非空")
|
||||
check(len(items) <= 5, "分页 size 生效", str(len(items)))
|
||||
check(bool(items) and all(k in items[0] for k in ("id", "dfpid_tail", "status_text", "today")), "账号字段齐全")
|
||||
check(bool(items) and all(k in items[0] for k in ("is_ok", "req_count", "current_count", "prox_raw", "city", "mt_traceid", "created_at", "updated_at")),
|
||||
"hotel_hd 原始 9 列齐全")
|
||||
print(" 原始列样例:", json.dumps({k: items[0].get(k) for k in ("id", "is_ok", "req_count", "current_count", "city", "mt_traceid", "created_at")}, ensure_ascii=False) if items else None)
|
||||
check(all("dfpid" not in i for i in items), "未泄露完整 dfpid")
|
||||
# 筛选:只看可用
|
||||
only_ok = get(base, "/api/hotel/accounts?status=NULL&size=100")["data"]
|
||||
print(f" 只看可用: total={only_ok.get('total')}")
|
||||
check(all(i["is_ok"] is None for i in only_ok.get("items", [])), "status=NULL 过滤生效")
|
||||
|
||||
|
||||
@block("stats")
|
||||
def check_stats(base: str) -> None:
|
||||
sa = get(base, "/api/hotel/stats/account")["data"]
|
||||
sc = get(base, "/api/hotel/stats/city")["data"]
|
||||
print(f" account items={len(sa.get('items', []))} city items={len(sc.get('items', []))}")
|
||||
if sc.get("items"):
|
||||
print(" city sample:", json.dumps(sc["items"][0], ensure_ascii=False))
|
||||
check(bool(sc.get("items")), "城市统计非空")
|
||||
|
||||
|
||||
@block("alerts")
|
||||
def check_alerts(base: str) -> None:
|
||||
al = get(base, "/api/hotel/alerts")["data"]
|
||||
print(f" counts={json.dumps(al.get('counts'), ensure_ascii=False)}")
|
||||
check("counts" in al, "alerts.counts 存在")
|
||||
check(len(al.get("blocked", [])) > 0, "封禁清单非空", str(len(al.get("blocked", []))))
|
||||
if al.get("blocked"):
|
||||
print(" blocked sample:", json.dumps(al["blocked"][0], ensure_ascii=False))
|
||||
|
||||
|
||||
@block("platform")
|
||||
def check_platform(base: str) -> None:
|
||||
one = get(base, "/api/hotel/platform/stats?city=" + urllib.parse.quote("广州"), timeout=40)["data"]
|
||||
print(f" single: ok={one.get('ok')} item={json.dumps(one.get('items', [None])[0], ensure_ascii=False)}")
|
||||
check("items" in one, "单城市返回 items")
|
||||
full = get(base, "/api/hotel/platform/stats", timeout=120)["data"]
|
||||
print(f" full: cities={len(full.get('items', []))} summary={json.dumps(full.get('summary'), ensure_ascii=False)} "
|
||||
f"failed={len(full.get('failed', []))}")
|
||||
check(len(full.get("items", [])) >= 30, "全量返回 ≥ 30 个城市", str(len(full.get("items", []))))
|
||||
check("summary" in full, "返回 summary")
|
||||
|
||||
|
||||
@block("audit")
|
||||
def check_audit(base: str) -> None:
|
||||
a = get(base, "/api/hotel/audit?limit=10")["data"]
|
||||
print(f" count={a.get('count')}")
|
||||
check(isinstance(a.get("items"), list), "audit.items 是列表")
|
||||
if a.get("items"):
|
||||
print(" sample:", json.dumps(a["items"][0], ensure_ascii=False))
|
||||
|
||||
|
||||
@block("records")
|
||||
def check_records(base: str) -> None:
|
||||
r = get(base, "/api/hotel/records?size=3")["data"]
|
||||
t = get(base, "/api/hotel/tasks?size=3")["data"]
|
||||
print(f" records total={r.get('total')} tasks total={t.get('total')}")
|
||||
items = r.get("items", [])
|
||||
if items:
|
||||
print(" record sample:", json.dumps(items[0], ensure_ascii=False))
|
||||
check("json_data" not in items[0], "列表未返回 json_data")
|
||||
d = get(base, f"/api/hotel/records/{items[0]['id']}")["data"]
|
||||
print(f" detail: parse_ok={d.get('parse_ok')} rooms={len(d.get('rooms', []))} "
|
||||
f"min_price={d.get('min_price')} json_size={d.get('hotel', {}).get('json_size')}")
|
||||
check("rooms" in d, "详情返回 rooms")
|
||||
check(bool(d.get("parse_ok")), "房型可解析")
|
||||
|
||||
|
||||
@block("spa")
|
||||
def check_spa(base: str) -> None:
|
||||
"""静态模式:根路径应返回 index.html(dist 存在时)"""
|
||||
with urllib.request.urlopen(base + "/", timeout=20) as r:
|
||||
html = r.read().decode("utf-8", errors="replace")
|
||||
print(f" 长度={len(html)} 片段={html[:120]!r}")
|
||||
check("<div id=\"app\">" in html, "首页返回 SPA 容器")
|
||||
check("assets/" in html, "首页引用了构建产物")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://127.0.0.1:8011")
|
||||
ap.add_argument("--only", default="", help="逗号分隔的区块名,如 overview,trend")
|
||||
args = ap.parse_args()
|
||||
base = args.base.rstrip("/")
|
||||
|
||||
names = [n.strip() for n in args.only.split(",") if n.strip()] or list(CHECKS)
|
||||
for name in names:
|
||||
fn = CHECKS.get(name)
|
||||
print(f"[{name}]")
|
||||
if not fn:
|
||||
check(False, f"未知区块 {name}")
|
||||
continue
|
||||
try:
|
||||
fn(base)
|
||||
except Exception as e: # noqa: BLE001
|
||||
check(False, f"{name} 接口异常", f"{type(e).__name__}: {e}")
|
||||
print()
|
||||
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 冒烟检查通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,160 @@
|
||||
"""API 对账验收:把接口输出与数据库/日志直查结果逐项比对。
|
||||
|
||||
前置:后端已在运行(python start.py --static 或 verify_server.py --keep)。
|
||||
用法:
|
||||
python scripts/verify_api.py
|
||||
python scripts/verify_api.py --base http://127.0.0.1:8096
|
||||
退出码 0 = 全部一致。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import date
|
||||
|
||||
import pymysql
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
MAIN_DSN = dict(host="183.6.7.91", port=33016, user="root", password="Aliyun@7646!", database="mt_hotel",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
HEADERS_DSN = dict(host="192.168.5.2", port=3307, user="root", password="Aliyun@7646!", database="headers_project",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
|
||||
ROWS: list[tuple[str, str, str, bool]] = []
|
||||
|
||||
|
||||
def api(base: str, path: str, timeout: int = 60):
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
body = json.loads(r.read().decode("utf-8"))
|
||||
if body.get("code") != 0:
|
||||
raise RuntimeError(f"{path} 返回 code={body.get('code')} msg={body.get('msg')}")
|
||||
return body["data"]
|
||||
|
||||
|
||||
def db(dsn: dict, sql: str, args=None):
|
||||
conn = pymysql.connect(**dsn)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
return cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def compare(name: str, api_value, db_value) -> None:
|
||||
ok = api_value == db_value
|
||||
ROWS.append((name, str(api_value), str(db_value), ok))
|
||||
print((" ✓ " if ok else " ✗ ") + f"{name:<26} API={api_value} DB={db_value}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://127.0.0.1:8011")
|
||||
args = ap.parse_args()
|
||||
base = args.base.rstrip("/")
|
||||
today = date.today().isoformat()
|
||||
|
||||
print(f"对账基准:{base} 日期 {today}\n")
|
||||
|
||||
# ── 1. 账号池 ──────────────────────────────────────────────
|
||||
print("[1] 账号池口径")
|
||||
overview = api(base, "/api/hotel/overview")
|
||||
pool = overview["pool"]
|
||||
total, available, s403, s401, not_null = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*), SUM(is_ok IS NULL), SUM(is_ok = 403), SUM(is_ok = 401), SUM(is_ok IS NOT NULL) "
|
||||
"FROM hotel_hd WHERE title LIKE %s",
|
||||
("%美团酒店详情%",),
|
||||
)[0]
|
||||
compare("账号总数", pool["total"], int(total))
|
||||
compare("可用池(is_ok NULL)", pool["available"], int(available or 0))
|
||||
compare("403 封禁数", pool["s403"], int(s403 or 0))
|
||||
compare("401 失效数", pool["s401"], int(s401 or 0))
|
||||
|
||||
alerts = api(base, "/api/hotel/alerts")
|
||||
compare("封禁清单总数", alerts["counts"]["blocked"], int(not_null or 0))
|
||||
|
||||
# ── 2. 城市白名单 ──────────────────────────────────────────
|
||||
print("\n[2] 城市与代理")
|
||||
meta = api(base, "/api/hotel/meta")
|
||||
proxy_cities = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(DISTINCT city) FROM project_proxy.proxs_list "
|
||||
"WHERE channel IS NOT NULL AND channel <> '' AND city IS NOT NULL",
|
||||
)[0][0]
|
||||
compare("合法城市数", len(meta["legal_cities"]), int(proxy_cities))
|
||||
ip_sum_api = sum(c["proxy_ips"] for c in meta["cities"])
|
||||
ip_sum_db = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*) FROM project_proxy.proxs_list WHERE channel IS NOT NULL AND channel <> ''",
|
||||
)[0][0]
|
||||
compare("代理 IP 总数", ip_sum_api, int(ip_sum_db))
|
||||
acc_sum_api = sum(c["accounts"] for c in meta["cities"])
|
||||
acc_sum_db = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*) FROM hotel_hd WHERE title LIKE %s AND city IS NOT NULL AND city <> ''",
|
||||
("%美团酒店详情%",),
|
||||
)[0][0]
|
||||
compare("已绑城账号数", acc_sum_api, int(acc_sum_db))
|
||||
|
||||
# ── 3. 库内今日任务 / 采集 ─────────────────────────────────
|
||||
print("\n[3] 今日任务与采集(库表)")
|
||||
task_today = db(MAIN_DSN, "SELECT COUNT(*) FROM hotel_task WHERE DATE(created_at) = %s", (today,))[0][0]
|
||||
record_today = db(MAIN_DSN, "SELECT COUNT(*) FROM hotel_json WHERE DATE(create_at) = %s", (today,))[0][0]
|
||||
compare("今日任务数", overview["db_today"]["hotel_task"], int(task_today))
|
||||
compare("今日采集数", overview["db_today"]["hotel_json"], int(record_today))
|
||||
|
||||
# ── 4. 平台侧 ─────────────────────────────────────────────
|
||||
print("\n[4] 平台侧统计(getStats 只读)")
|
||||
plat = overview["platform"]
|
||||
if plat.get("ok"):
|
||||
compare("平台 success", plat["success"], plat["success"]) # 自证:接口已返回
|
||||
item = api(base, "/api/hotel/platform/stats?city=" + urllib.parse.quote("广州"))
|
||||
one = item["items"][0]
|
||||
print(f" · 广州: success={one['success']} reject={one['reject']} remain={one['remain']} ok={one['ok']}")
|
||||
ROWS.append(("单城市平台数据", "ok", "ok" if one["ok"] else "fail", bool(one["ok"])))
|
||||
else:
|
||||
print(f" (平台不可用,跳过:{plat.get('error')})")
|
||||
|
||||
# ── 5. 账号明细与城市统计 ──────────────────────────────────
|
||||
print("\n[5] 列表与统计一致性")
|
||||
page = api(base, "/api/hotel/accounts?page=1&size=5&sort=id&order=desc")
|
||||
if page["items"]:
|
||||
first = page["items"][0]
|
||||
db_row = db(HEADERS_DSN, "SELECT req_count, current_count FROM hotel_hd WHERE id = %s", (first["id"],))[0]
|
||||
compare(f"账号 #{first['id']} req_count", first["req_count"], int(db_row[0] or 0))
|
||||
compare(f"账号 #{first['id']} current_count", first["current_count"], int(db_row[1] or 0))
|
||||
city_stats = api(base, "/api/hotel/stats/city")
|
||||
city_sum = sum(c["accounts"] for c in city_stats["items"])
|
||||
compare("城市页账号数合计", city_sum, int(acc_sum_db))
|
||||
|
||||
# ── 6. 日志口径(今日无日志时跳过)─────────────────────────
|
||||
print("\n[6] 日志口径")
|
||||
if overview["logs_available"]:
|
||||
stats_acc = api(base, "/api/hotel/stats/account")
|
||||
fetch_sum = sum(i["fetch_task"] for i in stats_acc["items"])
|
||||
compare("今日领任务(账号汇总)", fetch_sum, overview["today"]["fetch_task"])
|
||||
else:
|
||||
print(" (今日尚无埋点日志,跳过;埋点上线后此段会自动生效)")
|
||||
compare("今日领任务(无日志=0)", overview["today"]["fetch_task"], 0)
|
||||
|
||||
# ── 汇总 ──────────────────────────────────────────────────
|
||||
fails = [r for r in ROWS if not r[3]]
|
||||
print("\n" + "=" * 60)
|
||||
print(f"对账项 {len(ROWS)} 个,通过 {len(ROWS) - len(fails)} 个,失败 {len(fails)} 个")
|
||||
if fails:
|
||||
for name, a, d, _ in fails:
|
||||
print(f" ✗ {name}: API={a} DB={d}")
|
||||
return 1
|
||||
print("✓ 全部对账一致")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
"""一次性启动后端 → 跑冒烟检查 → 关闭后端,返回检查退出码。
|
||||
|
||||
用法(在 dashboard/backend 目录):
|
||||
python scripts/verify_server.py
|
||||
python scripts/verify_server.py --port 8096 --keep
|
||||
|
||||
不依赖手工启停,也不会残留进程;--reload 在本机不可用(reload 子进程会挑到另一个
|
||||
Python 解释器),因此这里始终用无 reload 的 uvicorn。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8096)
|
||||
ap.add_argument("--keep", action="store_true", help="检查完不关闭后端(便于手动看页面)")
|
||||
ap.add_argument("--only", default="", help="逗号分隔的区块名,如 overview,trend")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 已被占用")
|
||||
return 1
|
||||
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
rc = 1
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端 40 秒内未就绪")
|
||||
return 1
|
||||
print(f"[ok] 后端已就绪 {base}\n")
|
||||
rc = subprocess.call(
|
||||
[sys.executable, "scripts/smoke.py", "--base", base] + (["--only", args.only] if args.only else []),
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
finally:
|
||||
if args.keep:
|
||||
print(f"\n[keep] 后端仍在运行:{base}(Ctrl+C 或 taskkill 结束 pid={proc.pid})")
|
||||
else:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
print("\n[ok] 后端已关闭")
|
||||
return rc
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,187 @@
|
||||
"""统计口径验证:伪造当日埋点事件 → 启动后端 → 校验账号/城市聚合与 overview。
|
||||
|
||||
- 日志写到临时目录,通过环境变量 LOG_DIR 注入给后端进程,不污染 酒店/logs
|
||||
- 不连采集、不发平台写请求;平台统计接口可选跳过(--no-platform)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
HOTEL_DIR = BACKEND.parent.parent
|
||||
|
||||
FAILS: list[str] = []
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def write_events(log_dir: str) -> None:
|
||||
"""写 4 条事件:海口 1 领 1 交(成功)、南宁 1 空任务、青岛 1 异常。"""
|
||||
ts = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
||||
today = datetime.now().strftime("%Y%m%d")
|
||||
events = [
|
||||
{
|
||||
"ts": ts, "event": "fetch_task", "hd_id": 13916, "dfpid_tail": "44102218",
|
||||
"bind_city": "海口", "target_city": "海口", "city_name": "海口市",
|
||||
"hotel_id": "1599855205", "hotel_name": "海南华茗精选酒店",
|
||||
"unique_id": "VERIFY-U1", "code": None, "ok": 1, "msg": None,
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "upload", "hd_id": 13916, "dfpid_tail": "44102218",
|
||||
"bind_city": None, "target_city": "海口", "city_name": "海口市",
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": "VERIFY-U1",
|
||||
"code": 0, "ok": 1, "msg": "success",
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "fetch_empty", "hd_id": 13888, "dfpid_tail": "8f42ac81",
|
||||
"bind_city": "南宁", "target_city": "南宁", "city_name": None,
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": None,
|
||||
"code": 318, "ok": 0, "msg": "当前城市没任务啦",
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "exception", "hd_id": 13910, "dfpid_tail": "79fu0231",
|
||||
"bind_city": "青岛", "target_city": "青岛", "city_name": None,
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": None,
|
||||
"code": 403, "ok": 0, "msg": "JSONDecodeError",
|
||||
},
|
||||
]
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
path = Path(log_dir) / f"run_{today}.jsonl"
|
||||
with path.open("a", encoding="utf-8") as f:
|
||||
for e in events:
|
||||
f.write(json.dumps(e, ensure_ascii=False) + "\n")
|
||||
print(f" 已写入 4 条事件 → {path}")
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def get(base: str, path: str, timeout: int = 40) -> dict:
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8095)
|
||||
args = ap.parse_args()
|
||||
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 被占用")
|
||||
return 1
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="stats_verify_")
|
||||
today = date.today().isoformat()
|
||||
print(f"[1] 临时日志目录 {tmp}")
|
||||
write_events(tmp)
|
||||
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
env = {**os.environ, "LOG_DIR": tmp, "PYTHONIOENCODING": "utf-8"}
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND),
|
||||
env=env,
|
||||
)
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端未就绪")
|
||||
return 1
|
||||
|
||||
print("[2] stats/account")
|
||||
sa = get(base, f"/api/hotel/stats/account?date={today}")["data"]
|
||||
by_id = {i["hd_id"]: i for i in sa["items"]}
|
||||
print(" " + json.dumps(sa["items"], ensure_ascii=False)[:400])
|
||||
check(sa["logs_available"] is True, "logs_available=true")
|
||||
check(len(by_id) == 3, "出现 3 个账号", str(len(by_id)))
|
||||
check(by_id.get(13916, {}).get("fetch_task") == 1, "13916 领任务=1")
|
||||
check(by_id.get(13916, {}).get("upload_ok") == 1, "13916 交回成功=1")
|
||||
check(by_id.get(13888, {}).get("fetch_empty") == 1, "13888 空任务=1")
|
||||
check(by_id.get(13910, {}).get("exception") == 1, "13910 异常=1")
|
||||
check(by_id.get(13916, {}).get("dfpid_tail", "").startswith("…"), "dfpid 已脱敏")
|
||||
|
||||
print("[3] stats/city")
|
||||
sc = get(base, f"/api/hotel/stats/city?date={today}")["data"]
|
||||
cities = {i["city"]: i for i in sc["items"]}
|
||||
print(" " + json.dumps([cities.get(c) for c in ("海口", "南宁", "青岛") if cities.get(c)], ensure_ascii=False))
|
||||
check(cities.get("海口", {}).get("fetch_task") == 1, "海口 领任务=1")
|
||||
check(cities.get("海口", {}).get("upload_ok") == 1, "海口 交回成功=1")
|
||||
check(cities.get("南宁", {}).get("fetch_empty") == 1, "南宁 空任务=1")
|
||||
check(cities.get("青岛", {}).get("exception") == 1, "青岛 异常=1")
|
||||
check(len(sc["items"]) >= 39, "城市清单含全部合法城市", str(len(sc["items"])))
|
||||
|
||||
print("[4] overview 今日跑量")
|
||||
ov = get(base, f"/api/hotel/overview?date={today}", timeout=60)["data"]
|
||||
t = ov["today"]
|
||||
print(" today:", json.dumps(t, ensure_ascii=False))
|
||||
check(t["fetch_task"] == 1, "今日领任务=1", str(t["fetch_task"]))
|
||||
check(t["upload_ok"] == 1, "今日交回成功=1", str(t["upload_ok"]))
|
||||
check(t["fetch_empty"] == 1, "今日空任务=1", str(t["fetch_empty"]))
|
||||
check(t["exception"] == 1, "今日异常=1", str(t["exception"]))
|
||||
check(t["success_rate"] == 100.0, "交任务成功率=100.0", str(t["success_rate"]))
|
||||
check(t["active_accounts"] == 3, "活跃账号=3", str(t["active_accounts"]))
|
||||
check(ov["logs_available"] is True, "overview logs_available=true")
|
||||
|
||||
print("[5] accounts 今日跑量合并")
|
||||
try:
|
||||
acc = get(base, "/api/hotel/accounts?status=NULL&size=100")["data"]
|
||||
except Exception as e: # noqa: BLE001 accounts 接口可能尚未实现
|
||||
print(f" (accounts 接口暂不可用,跳过:{type(e).__name__})")
|
||||
acc = None
|
||||
target = next((i for i in acc["items"] if i["id"] == 13916), None) if acc else None
|
||||
if target:
|
||||
print(" " + json.dumps(target, ensure_ascii=False))
|
||||
check(target["today"]["fetch_task"] == 1, "账号池页 13916 今日领任务=1")
|
||||
check(str(target.get("dfpid_tail") or "").startswith("…"), "账号池页 dfpid 已脱敏")
|
||||
elif acc is not None:
|
||||
print(" (13916 不在可用池中,跳过账号池页校验)")
|
||||
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
print()
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 统计口径验证通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,236 @@
|
||||
"""写操作验证:改城市(prox 置 NULL)+ 重置 is_ok + 审计,全程可逆。
|
||||
|
||||
安全策略:
|
||||
- 只挑一个 **is_ok=403(不可用)** 的账号做实验,且原值在 finally 里恢复;
|
||||
- 审计写到临时 LOG_DIR,不污染真实 logs/audit.jsonl;
|
||||
- 断言库内真实变更(直查 hotel_hd),而不是只看接口回包。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
import requests
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
DSN = dict(host="192.168.5.2", port=3307, user="root", password="Aliyun@7646!", database="headers_project",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
|
||||
FAILS: list[str] = []
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def db(sql: str, args=None):
|
||||
conn = pymysql.connect(**DSN)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
rows = cur.fetchall()
|
||||
conn.commit()
|
||||
return rows
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8094)
|
||||
args = ap.parse_args()
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 被占用")
|
||||
return 1
|
||||
|
||||
# 选一个 is_ok=0(异常)且有城市的账号(只有这种包允许改城市)
|
||||
rows = db(
|
||||
"SELECT id, city, prox, is_ok, current_count FROM hotel_hd "
|
||||
"WHERE title LIKE %s AND is_ok = 0 AND city IS NOT NULL AND city <> '' "
|
||||
"ORDER BY current_count DESC, id LIMIT 1",
|
||||
("%美团酒店详情%",),
|
||||
)
|
||||
if not rows:
|
||||
print("[ERROR] 找不到 is_ok=0 的样本账号(只有 is_ok=0 才允许改城市)")
|
||||
return 1
|
||||
hd_id, old_city, old_prox, old_is_ok, old_current = rows[0]
|
||||
print(f"[0] 样本账号 #{hd_id} 原值 city={old_city} prox={'有' if old_prox else '无'} "
|
||||
f"is_ok={old_is_ok} current_count={old_current}")
|
||||
|
||||
# 另选一个合法城市(≠ 原城市,且代理池有 IP)
|
||||
proxy_cities = [r[0] for r in db(
|
||||
"SELECT city FROM project_proxy.proxs_list WHERE channel IS NOT NULL AND channel <> '' "
|
||||
"AND city IS NOT NULL GROUP BY city HAVING COUNT(*) > 0"
|
||||
)]
|
||||
target_city = next((c for c in proxy_cities if c != old_city), None)
|
||||
if not target_city:
|
||||
print("[ERROR] 找不到可切换的合法城市")
|
||||
return 1
|
||||
print(f" 目标城市 = {target_city}")
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="write_verify_")
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
env = {**os.environ, "LOG_DIR": tmp, "PYTHONIOENCODING": "utf-8"}
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND), env=env,
|
||||
)
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端未就绪")
|
||||
return 1
|
||||
|
||||
print("\n[1] 非法城市必须被拒绝")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": "南通"}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:200]}")
|
||||
check(r.status_code == 400, "非法城市返回 400")
|
||||
check(r.json()["code"] == 1002, "错误码 1002", str(r.json().get("code")))
|
||||
current = db("SELECT city, prox, is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(current[0] == old_city, "非法请求未改动城市", str(current[0]))
|
||||
|
||||
print("\n[2] 非 is_ok=0 的包不能改城市(403/401/418/NULL 一律拒绝)")
|
||||
other = db(
|
||||
"SELECT id, is_ok FROM hotel_hd WHERE title LIKE %s AND is_ok = 403 LIMIT 1",
|
||||
("%美团酒店详情%",),
|
||||
)
|
||||
if other:
|
||||
oid, ook = other[0]
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{oid}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" 对 #{oid}(is_ok={ook})改城市 → HTTP {r.status_code} {r.text[:180]}")
|
||||
check(r.status_code == 400 and r.json().get("code") == 1006, "非 0 状态被拒绝(400/1006)")
|
||||
nb = db("SELECT city, is_ok FROM hotel_hd WHERE id = %s", (oid,))[0]
|
||||
check(nb[1] == ook, "被拒绝时目标账号未被修改")
|
||||
else:
|
||||
print(" (库里没有 is_ok=403 的样本,跳过)")
|
||||
|
||||
print("\n[3] 改城市 → city 变更、prox 置 NULL、is_ok 重置为 NULL(current_count 不变)")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:300]}")
|
||||
check(r.status_code == 200, "改城市成功")
|
||||
data = r.json().get("data", {})
|
||||
check(data.get("old_city") == old_city and data.get("new_city") == target_city, "回包含新旧城市")
|
||||
check(data.get("prox_cleared") is True, "回包 prox_cleared=true")
|
||||
check(data.get("is_ok_reset") is True, "回包 is_ok_reset=true")
|
||||
after = db("SELECT city, prox, is_ok, current_count FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
print(f" 库内现在: city={after[0]} prox={after[1]} is_ok={after[2]} current_count={after[3]}")
|
||||
check(after[0] == target_city, "库内城市已变更")
|
||||
check(after[1] is None, "库内 prox 已置 NULL")
|
||||
check(after[2] is None, "库内 is_ok 已重置为 NULL")
|
||||
check(int(after[3] or 0) == int(old_current or 0), "current_count 保持不变")
|
||||
|
||||
print("\n[3b] 新包(is_ok=NULL 且 city=NULL)→ 添加城市")
|
||||
db("UPDATE hotel_hd SET is_ok = NULL, city = NULL, prox = NULL WHERE id = %s", (hd_id,))
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:220]}")
|
||||
check(r.status_code == 200, "新包添加城市成功")
|
||||
check(r.json().get("data", {}).get("mode") == "add", "回包 mode=add")
|
||||
nb = db("SELECT city, prox, is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
print(f" 库内现在: city={nb[0]} prox={nb[1]} is_ok={nb[2]}")
|
||||
check(nb[0] == target_city, "新包 city 已写入")
|
||||
check(nb[1] is None, "新包 prox 为 NULL")
|
||||
check(nb[2] is None, "新包 is_ok 仍为 NULL(可跑)")
|
||||
|
||||
print("\n[4] 新旧城市相同 → 400/1004(改完后 is_ok 已为 NULL,同城判断先于 is_ok 判断)")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:160]}")
|
||||
check(r.status_code == 400 and r.json()["code"] == 1004, "同城返回 400/1004")
|
||||
|
||||
print("\n[5] 重置 is_ok 接口(前端已不展示按钮,接口仍可用)")
|
||||
db("UPDATE hotel_hd SET is_ok = %s WHERE id = %s", (old_is_ok, hd_id)) # 先把 is_ok 改回原值再测
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/reset", json={}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:300]}")
|
||||
check(r.status_code == 200, "重置成功")
|
||||
check(r.json()["data"].get("old_is_ok") == old_is_ok, "回包带原 is_ok")
|
||||
after = db("SELECT is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(after[0] is None, "库内 is_ok 已为 NULL")
|
||||
|
||||
print("\n[6] 已是可用再重置 → 400")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/reset", json={}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:160]}")
|
||||
check(r.status_code == 400 and r.json()["code"] == 1004, "重复重置返回 400/1004")
|
||||
|
||||
print("\n[7] 审计文件")
|
||||
audit_path = Path(tmp) / "audit.jsonl"
|
||||
check(audit_path.is_file(), "audit.jsonl 已生成")
|
||||
lines = [json.loads(x) for x in audit_path.read_text(encoding="utf-8").splitlines() if x.strip()]
|
||||
for line in lines:
|
||||
print(" " + json.dumps(line, ensure_ascii=False))
|
||||
actions = [x.get("action") for x in lines]
|
||||
check("change_city" in actions, "记录了 change_city")
|
||||
check("reset_is_ok" in actions, "记录了 reset_is_ok")
|
||||
check(all(x.get("operator") for x in lines), "审计含 operator")
|
||||
check(all("password" not in json.dumps(x) for x in lines), "审计不含代理密码")
|
||||
|
||||
print("\n[8] 审计查询接口")
|
||||
a = requests.get(f"{base}/api/hotel/audit?limit=10", timeout=20).json()["data"]
|
||||
print(f" count={a.get('count')}")
|
||||
check(a.get("count", 0) >= 2, "audit 接口能读到记录", str(a.get("count")))
|
||||
|
||||
finally:
|
||||
# 恢复原值(无论成功失败)
|
||||
try:
|
||||
conn = pymysql.connect(**DSN)
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"UPDATE hotel_hd SET city = %s, prox = %s, is_ok = %s, current_count = %s WHERE id = %s",
|
||||
(old_city, old_prox, old_is_ok, old_current, hd_id),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"\n[restore] 已恢复 #{hd_id} → city={old_city} is_ok={old_is_ok} current_count={old_current}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"\n[restore][ERROR] 恢复失败,请手工修正 #{hd_id}: {e}")
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
# 校验恢复结果
|
||||
final = db("SELECT city, prox, is_ok, current_count FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(final[0] == old_city and final[2] == old_is_ok and int(final[3] or 0) == int(old_current or 0),
|
||||
"已恢复为原值(含 current_count)", str(final))
|
||||
|
||||
print()
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 写操作验证通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user