#!/usr/bin/env python3 """HTTP GET: статус, время ответа и разбор JSON.""" 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 header_pair(value: str) -> tuple[str, str]: if ":" not in value: raise argparse.ArgumentTypeError("Заголовок должен быть в формате 'Name: value'") name, text = value.split(":", 1) if not name.strip(): raise argparse.ArgumentTypeError("Пустое имя заголовка") return name.strip(), text.strip() def main() -> int: parser = argparse.ArgumentParser(description="Выполнить HTTP GET и показать результат") parser.add_argument("url", nargs="?", default="https://example.com/", help="Адрес запроса") parser.add_argument("--header", action="append", type=header_pair, default=[], metavar="NAME:VALUE") parser.add_argument("--timeout", type=float, default=10.0, help="Таймаут в секундах") parser.add_argument("--max-bytes", type=int, default=2_000_000, help="Лимит тела ответа") parser.add_argument("--output", type=Path, help="Сохранить тело ответа") parser.add_argument("--json", action="store_true", help="Разобрать ответ как JSON") args = parser.parse_args() headers = { "User-Agent": "popovdev-scriptdock/1.0", "Accept": "application/json, text/html;q=0.9, */*;q=0.8", } for name, value in args.header: headers[name] = value request = Request(args.url, headers=headers) started = time.perf_counter() try: with urlopen(request, timeout=args.timeout) as response: body = response.read(args.max_bytes) status = response.status reason = response.reason content_type = response.headers.get("Content-Type", "") except HTTPError as error: body = error.read(args.max_bytes) status = error.code reason = error.reason content_type = error.headers.get("Content-Type", "") if error.headers else "" except URLError as error: print(f"Не удалось подключиться: {error.reason}") return 2 elapsed = (time.perf_counter() - started) * 1000 print(f"Статус: {status} {reason}") print(f"Время: {elapsed:.0f} мс") print(f"Content-Type: {content_type or 'не указан'}") print(f"Размер: {len(body)} байт") if args.output: args.output.write_bytes(body) print(f"Сохранено: {args.output}") if args.json: try: data = json.loads(body.decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError) as error: print(f"JSON не разобран: {error}") return 1 print(json.dumps(data, ensure_ascii=False, indent=2)[:8000]) else: print(body.decode("utf-8", errors="replace")[:2000]) return 0 if status < 400 else 1 if __name__ == "__main__": raise SystemExit(main())