|
@@ -13,21 +13,38 @@ if typing.TYPE_CHECKING:
|
|
|
CACHE_DIR = pathlib.Path(__file__).parent / 'cache'
|
|
CACHE_DIR = pathlib.Path(__file__).parent / 'cache'
|
|
|
client = httpx.Client(transport=httpx.HTTPTransport(http2=True, retries=2), timeout=10)
|
|
client = httpx.Client(transport=httpx.HTTPTransport(http2=True, retries=2), timeout=10)
|
|
|
|
|
|
|
|
-def get(url: str, *, headers: httpx._types.HeaderTypes|None=None) -> typing.Any:
|
|
|
|
|
|
|
+@typing.overload
|
|
|
|
|
+def get(url: str, *, json: typing.Literal[True]=True, headers: httpx._types.HeaderTypes|None=None) -> typing.Any:
|
|
|
|
|
+ ...
|
|
|
|
|
+@typing.overload
|
|
|
|
|
+def get(url: str, *, json: typing.Literal[False], headers: httpx._types.HeaderTypes|None=None) -> str:
|
|
|
|
|
+ ...
|
|
|
|
|
+def get(url: str, *, json=True, headers=None) -> typing.Any:
|
|
|
parsed = urllib.parse.urlparse(url)
|
|
parsed = urllib.parse.urlparse(url)
|
|
|
assert parsed.hostname is not None
|
|
assert parsed.hostname is not None
|
|
|
- cache_path = CACHE_DIR / parsed.hostname / (urllib.parse.quote(parsed.path.removeprefix('/'), safe='') + '.cbor.xz')
|
|
|
|
|
|
|
+ cache_filename = urllib.parse.quote(parsed.path.removeprefix('/'), safe='')
|
|
|
|
|
+ if json:
|
|
|
|
|
+ cache_filename += '.cbor'
|
|
|
|
|
+ cache_filename += '.xz'
|
|
|
|
|
+ cache_path = CACHE_DIR / parsed.hostname / cache_filename
|
|
|
|
|
|
|
|
try:
|
|
try:
|
|
|
if cache_path.stat().st_mtime > time.time() - 600: # less than 10 minutes old
|
|
if cache_path.stat().st_mtime > time.time() - 600: # less than 10 minutes old
|
|
|
with lzma.open(cache_path, 'rb') as f:
|
|
with lzma.open(cache_path, 'rb') as f:
|
|
|
- return cbor2.load(f)
|
|
|
|
|
|
|
+ if json:
|
|
|
|
|
+ return cbor2.load(f)
|
|
|
|
|
+ else:
|
|
|
|
|
+ return f.read().decode('utf-8')
|
|
|
except FileNotFoundError:
|
|
except FileNotFoundError:
|
|
|
pass # fall through
|
|
pass # fall through
|
|
|
|
|
|
|
|
r = client.get(url, headers=headers).raise_for_status()
|
|
r = client.get(url, headers=headers).raise_for_status()
|
|
|
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
with lzma.open(cache_path, 'wb') as f:
|
|
with lzma.open(cache_path, 'wb') as f:
|
|
|
- data = r.json()
|
|
|
|
|
- cbor2.dump(data, f)
|
|
|
|
|
|
|
+ if json:
|
|
|
|
|
+ data = r.json()
|
|
|
|
|
+ cbor2.dump(data, f)
|
|
|
|
|
+ else:
|
|
|
|
|
+ data = r.text
|
|
|
|
|
+ f.write(data.encode('utf-8'))
|
|
|
return data
|
|
return data
|