#!/usr/bin/env python3 """Один запрос с разбором rate limit и повторами.""" from __future__ import annotations import argparse import json import time from pathlib import Path from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen def parse_retry_after(value: str | None, default: float) -> float: if not value: return default try: return max(0.0, float(value)) except ValueError: return default def main() -> int: parser = argparse.ArgumentParser(description="Разобрать лимиты API") parser.add_argument("url", help="Адрес API") parser.add_argument("--max-retries", type=int, default=2) parser.add_argument("--max-wait", type=float, default=30.0) parser.add_argument("--timeout", type=float, default=10.0) parser.add_argument("--output", type=Path, help="Сохранить тело ответа") parser.add_argument("--json", action="store_true", help="Показать тело как JSON") args = parser.parse_args() status = None body = b"" headers: dict[str, str] = {} for attempt in range(1, args.max_retries + 2): request = Request( args.url, headers={"Accept": "application/json", "User-Agent": "popovdev-scriptdock/1.0"}, ) try: with urlopen(request, timeout=args.timeout) as response: status = response.status body = response.read(2_000_000) headers = {key.lower(): value for key, value in response.headers.items()} except HTTPError as error: status = error.code body = error.read(2_000_000) headers = {key.lower(): value for key, value in (error.headers or {}).items()} except URLError as error: print(f"Не удалось подключиться: {error.reason}") return 2 print(f"Попытка {attempt}: статус {status}") for key in ("ratelimit-limit", "ratelimit-remaining", "ratelimit-reset", "x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset"): if key in headers: print(f" {key}: {headers[key]}") if status not in {429, 503}: break if attempt > args.max_retries: print("Повторы закончились") break wait = parse_retry_after(headers.get("retry-after"), 2.0 * attempt) wait = min(wait, args.max_wait) print(f" пауза {wait:.1f} с") time.sleep(wait) if args.output: args.output.write_bytes(body) print(f"Сохранено: {args.output}") text = body.decode("utf-8", errors="replace") if args.json: try: print(json.dumps(json.loads(text), ensure_ascii=False, indent=2)[:8000]) except json.JSONDecodeError: print("Ответ не является JSON") print(text[:1000]) else: print(text[:2000]) return 0 if status is not None and status < 400 else 1 if __name__ == "__main__": raise SystemExit(main())