mirror of
https://github.com/glomatico/gamdl.git
synced 2026-06-13 12:15:18 +03:00
Refactor utils to use httpx and simplify functions
This commit is contained in:
+12
-41
@@ -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 {}
|
||||
|
||||
Reference in New Issue
Block a user