Skip to content

Commit

Permalink
Add helper methods for HTTP
Browse files Browse the repository at this point in the history
  • Loading branch information
aivarannamaa committed Aug 15, 2024
1 parent 5e6289f commit a1fdaa6
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion thonny/misc_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit a1fdaa6

Please sign in to comment.