mirror of
https://github.com/DragoonAethis/itch-dl.git
synced 2025-02-01 22:32:37 +01:00
816a4d7399
Warns about various small code smells and odd issues we can catch early. Nothing here should change the program behavior directly.
61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
from typing import Optional, Any
|
|
|
|
import requests
|
|
from requests import Session
|
|
from urllib3.util.retry import Retry
|
|
from requests.adapters import HTTPAdapter
|
|
|
|
from .consts import ITCH_API
|
|
|
|
|
|
class ItchApiClient:
|
|
def __init__(self, api_key: str, user_agent: str, base_url: Optional[str] = None) -> None:
|
|
self.base_url = base_url or ITCH_API
|
|
self.api_key = api_key
|
|
|
|
self.requests = Session()
|
|
self.requests.headers["User-Agent"] = user_agent
|
|
|
|
retry_strategy = Retry(
|
|
total=5,
|
|
backoff_factor=10,
|
|
allowed_methods=["HEAD", "GET"],
|
|
status_forcelist=[429, 500, 502, 503, 504],
|
|
)
|
|
|
|
# No timeouts - set them explicitly on API calls below!
|
|
adapter = HTTPAdapter(max_retries=retry_strategy)
|
|
self.requests.mount("https://", adapter)
|
|
self.requests.mount("http://", adapter)
|
|
|
|
def get(
|
|
self,
|
|
endpoint: str,
|
|
append_api_key: bool = True,
|
|
guess_encoding: bool = False,
|
|
**kwargs: Any, # noqa: ANN401
|
|
) -> requests.Response:
|
|
"""Wrapper around `requests.get`.
|
|
|
|
:param endpoint: Path to fetch on the specified base URL.
|
|
:param append_api_key: Send an authenticated API request.
|
|
:param guess_encoding: Let requests guess the response encoding.
|
|
"""
|
|
if append_api_key:
|
|
params = kwargs.get("data") or {}
|
|
|
|
if "api_key" not in params:
|
|
params["api_key"] = self.api_key
|
|
|
|
kwargs["data"] = params
|
|
|
|
url = endpoint if endpoint.startswith("https://") else self.base_url + endpoint
|
|
r = self.requests.get(url, **kwargs)
|
|
|
|
# Itch always returns UTF-8 pages and API responses. Force
|
|
# UTF-8 everywhere, except for binary file downloads.
|
|
if not guess_encoding:
|
|
r.encoding = "utf-8"
|
|
|
|
return r
|