"""未登录接口按来源地址限速。状态只放内存。""" from __future__ import annotations import time _hits: dict[str, list[float]] = {} _WINDOW = 60.0 _LIMIT = 30 def reset() -> None: _hits.clear() def allow(source: str, limit: int = _LIMIT, window: float = _WINDOW) -> bool: now = time.monotonic() key = (source or "unknown").strip() or "unknown" recent = [item for item in _hits.get(key, []) if now - item < window] if len(recent) >= limit: _hits[key] = recent return False recent.append(now) _hits[key] = recent return True