Refactor utils to use httpx and simplify functions

This commit is contained in:
Rafael Moraes
2025-10-19 11:36:27 -03:00
parent 5c8e47fc76
commit 2935e873f9
+12 -41
View File
@@ -1,46 +1,17 @@
from pathlib import Path
import json
import click
import colorama
import requests
from .constants import X_NOT_FOUND_STRING
import httpx
def color_text(text: str, color) -> str:
return color + text + colorama.Style.RESET_ALL
def raise_for_status(httpx_response: httpx.Response, valid_responses: set[int] = {200}):
if httpx_response.status_code not in valid_responses:
raise httpx._exceptions.HTTPError(
f"HTTP error {httpx_response.status_code}: {httpx_response.text}"
)
def raise_response_exception(response: requests.Response):
raise Exception(
f"Request failed with status code {response.status_code}: {response.text}"
)
def prompt_path(is_file: bool, initial_path: Path, description: str) -> Path:
path_validator = click.Path(
exists=True,
file_okay=is_file,
dir_okay=not is_file,
path_type=Path,
)
path_type = "file" if is_file else "folder"
while True:
try:
path_obj = path_validator.convert(initial_path, None, None)
break
except click.BadParameter as e:
path_str = click.prompt(
(
f"{X_NOT_FOUND_STRING.format(description, initial_path.absolute())} or "
"the specified path is not valid. "
f"Move the {path_type} to that location, type a new path "
f"or drag and drop the {path_type} here. "
"Then, press enter to continue"
),
default=str(initial_path),
show_default=False,
)
path_str = path_str.strip('"')
initial_path = Path(path_str)
return path_obj
def safe_json(httpx_response: httpx.Response) -> dict:
try:
return httpx_response.json()
except (json.JSONDecodeError, UnicodeDecodeError):
return {}