#!/usr/bin/env python3 """HTTP POST с JSON-телом.""" from __future__ import annotations import argparse import json import os 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) return name.strip(), text.strip() def main() -> int: parser = argparse.ArgumentParser(description="Отправить JSON через POST") parser.add_argument("url", help="Адрес эндпоинта") parser.add_argument("--data", help="JSON-строка") parser.add_argument("--file", type=Path, help="Файл с JSON") parser.add_argument("--header", action="append", type=header_pair, default=[], metavar="NAME:VALUE") parser.add_argument("--timeout", type=float, default=15.0) parser.add_argument("--output", type=Path, help="Сохранить ответ") args = parser.parse_args() if bool(args.data) == bool(args.file): parser.error("Укажите ровно один источник: --data или --file") if args.file: if not args.file.is_file(): parser.error(f"Файл не найден: {args.file}") text = args.file.read_text(encoding="utf-8") else: text = args.data or "" try: payload = json.loads(text) except json.JSONDecodeError as error: parser.error(f"Некорректный JSON: {error}") body = json.dumps(payload, ensure_ascii=False).encode("utf-8") headers = { "Content-Type": "application/json; charset=utf-8", "Accept": "application/json, */*;q=0.8", "User-Agent": "popovdev-scriptdock/1.0", } for name, value in args.header: headers[name] = value token = os.environ.get("API_TOKEN", "") if token: headers.setdefault("Authorization", f"Bearer {token}") request = Request(args.url, data=body, headers=headers, method="POST") try: with urlopen(request, timeout=args.timeout) as response: status = response.status reason = response.reason answer = response.read(2_000_000) content_type = response.headers.get("Content-Type", "") except HTTPError as error: status = error.code reason = error.reason answer = error.read(2_000_000) content_type = error.headers.get("Content-Type", "") if error.headers else "" except URLError as error: print(f"Не удалось подключиться: {error.reason}") return 2 print(f"Статус: {status} {reason}") print(f"Отправлено: {len(body)} байт") print(f"Content-Type ответа: {content_type or 'не указан'}") if args.output: args.output.write_bytes(answer) print(f"Сохранено: {args.output}") text_answer = answer.decode("utf-8", errors="replace") if "json" in content_type.lower(): try: print(json.dumps(json.loads(text_answer), ensure_ascii=False, indent=2)[:8000]) except json.JSONDecodeError: print(text_answer[:2000]) else: print(text_answer[:2000]) return 0 if status < 400 else 1 if __name__ == "__main__": raise SystemExit(main())