From a1fdaa6e241844db3b35b0869a81786fa6c73083 Mon Sep 17 00:00:00 2001 From: Aivar Annamaa Date: Thu, 15 Aug 2024 22:24:31 +0300 Subject: [PATCH] Add helper methods for HTTP --- thonny/misc_utils.py | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/thonny/misc_utils.py b/thonny/misc_utils.py index d25a586d9..1b1fd243d 100644 --- a/thonny/misc_utils.py +++ b/thonny/misc_utils.py @@ -11,7 +11,7 @@ import threading import time from logging import getLogger -from typing import Any, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence from thonny.languages import tr @@ -600,6 +600,44 @@ def download_and_parse_json(url: str, timeout: int = 10) -> Any: return json.loads(download_bytes(url, timeout=timeout)) +def post_and_return_stream( + url: str, data: Any, headers: Dict[str, Any] = {}, timeout: int = 10 +) -> Any: + import json + from urllib.request import Request, urlopen + + if not isinstance(data, bytes): + if isinstance(data, str): + data = data.encode(encoding="utf-8") + else: + data = json.dumps(data).encode(encoding="utf-8") + + req = Request(url, headers={key: str(value) for key, value in headers.items()}) + + return urlopen(req, data=data, timeout=timeout) + + +def post_and_parse_json( + url: str, data: Any, headers: Dict[str, Any] = {}, timeout: int = 10 +) -> Any: + import json + + resp = post_and_return_stream( + url, data=data, headers={key: str(value) for key, value in headers.items()}, timeout=timeout + ) + return json.load(resp) + + +def get_and_parse_json(url: str, headers: Dict[str, Any] = {}, timeout: int = 10) -> Any: + import json + from urllib.request import Request, urlopen + + req = Request(url, headers=headers) + + resp = urlopen(req, timeout=timeout) + return json.load(resp) + + def get_os_level_favorite_folders() -> List[str]: if running_on_windows(): raise NotImplementedError()