StarRailDamageCal/starrail_damage_cal/mihomo/requests.py

39 lines
1.2 KiB
Python
Raw Normal View History

2023-10-30 06:31:15 +00:00
from __future__ import annotations
2023-12-27 05:43:17 +00:00
import json
2023-10-30 07:52:39 +00:00
from pathlib import Path
2023-12-27 05:43:17 +00:00
import msgspec
2023-10-30 06:31:15 +00:00
from httpx import AsyncClient
from msgspec import convert
2023-12-27 05:43:17 +00:00
from starrail_damage_cal.exception import MihomoModelError, MihomoQueueTimeoutError
2023-10-30 06:31:15 +00:00
from starrail_damage_cal.mihomo.models import MihomoData
_HEADER = {"User-Agent": "StarRailDamageCal/"}
2023-10-30 07:52:39 +00:00
async def get_char_card_info(
uid: str,
save_path: Path | None = None,
) -> MihomoData:
2023-10-30 06:31:15 +00:00
async with AsyncClient(
base_url="http://api.mihomo.me",
headers=_HEADER,
timeout=30,
) as client:
req = await client.get(f"/sr_info/{uid}")
2023-10-30 07:52:39 +00:00
if save_path:
2023-10-30 08:11:38 +00:00
path = save_path / str(uid)
path.mkdir(parents=True, exist_ok=True)
with Path.open(path / f"{uid!s}.json", "w") as file:
2023-10-30 07:52:39 +00:00
file.write(req.text)
2023-12-27 05:43:17 +00:00
try:
return convert(req.json(), type=MihomoData)
except msgspec.ValidationError as e:
if req.text == '{"detail":"Queue timeout"}':
raise MihomoQueueTimeoutError from e
raise MihomoModelError(e) from e
except json.decoder.JSONDecodeError as e:
raise MihomoModelError(e) from e