Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,28 @@ mope = Mope(token="test_123")
mope.shop.get_payment_request(payment_id="123")
```

### Timeouts and errors

Requests use a 5-second connect timeout and a 30-second read timeout by default.
Configure both with `Mope(token="test_123", timeout=(3.0, 15.0))`, or pass a
single number of seconds to apply to both. `mope.client.Client` accepts the same
keyword argument. Values must be finite and greater than zero. The read timeout
limits inactivity between received bytes, not the total duration of a request.

Shop methods raise `mope.errors.MopeAPIError` for HTTP errors. It is a subclass
of `requests.HTTPError`, so existing handlers keep working. Its `status_code`,
`code`, `message`, and `data` fields expose the HTTP status and validated Mopé
error details, such as code `1033` for account limits exceeded. If the error body
is missing or malformed, `code` and `data` are `None` and `message` retains the
HTTP error description. The original response and exception cause are preserved.

Connection failures and timeouts remain `requests.RequestException` subclasses.
Malformed successful responses still raise `TypeError`, `ValueError`, or
`KeyError`; invalid JSON raises `requests.exceptions.JSONDecodeError`, which is
also a `ValueError`. Applications should translate these errors at the API call
boundary and decide which failures are retryable. Requests are not automatically
retried, including payment creation after a timeout.

### Development

Install [uv](https://docs.astral.sh/uv/getting-started/installation/), then run:
Expand Down
2 changes: 1 addition & 1 deletion mope/__version__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__author__ = "lemuel@vokality.com"
__version__ = "0.3.0"
__version__ = "0.3.1"
40 changes: 35 additions & 5 deletions mope/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from collections.abc import Iterable, Mapping, Set
from math import isfinite
from typing import IO, Protocol, TypeAlias
from urllib.parse import urljoin

Expand Down Expand Up @@ -29,19 +30,45 @@ def items(self) -> Set[tuple[QueryScalar, QueryValue]]: ...
| str
| bytes
)
RequestTimeout: TypeAlias = float | tuple[float, float]

_user_agent = f"Python Mope {__version__}"
_BASE_URL = "https://api.mope.sr/api/"
_DEFAULT_TIMEOUT = (5.0, 30.0)


def _timeout_seconds(value: object) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError("timeout must contain numbers of seconds")
try:
seconds = float(value)
except OverflowError as error:
raise ValueError("timeout must be finite and greater than zero") from error
if not isfinite(seconds) or seconds <= 0:
raise ValueError("timeout must be finite and greater than zero")
return seconds


def _request_timeout(value: object) -> RequestTimeout:
if isinstance(value, tuple):
if len(value) != 2:
raise ValueError("timeout must be a (connect, read) pair")
return (_timeout_seconds(value[0]), _timeout_seconds(value[1]))
return _timeout_seconds(value)


class Client:
def __init__(self, token: str) -> None:
def __init__(
self, token: str, *, timeout: RequestTimeout = _DEFAULT_TIMEOUT
) -> None:
self._timeout = _request_timeout(timeout)
self._token = token
self._headers = {
"User-Agent": _user_agent,
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
}
self._base_url = "https://api.mope.sr/api"
self._base_url = _BASE_URL

def call_api(
self,
Expand All @@ -59,20 +86,23 @@ def call_api(
data=data,
json=json_value(json, path="request"),
headers=self._headers,
timeout=self._timeout,
)


class Mope:
def __init__(self, token: str) -> None:
def __init__(
self, token: str, *, timeout: RequestTimeout = _DEFAULT_TIMEOUT
) -> None:
self._token = token
self._headers = {
"User-Agent": _user_agent,
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
}
self.base_url = "https://api.mope.sr/api"
self.base_url = _BASE_URL

self._client = Client(token)
self._client = Client(token, timeout=timeout)

self.shop = ShopResource(self._client)

Expand Down
52 changes: 52 additions & 0 deletions mope/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Typed details for HTTP errors returned by the Mopé API."""

from typing import Self

from requests import HTTPError, Response

from mope.json import JsonValue, json_integer, json_object, json_string


class MopeAPIError(HTTPError):
"""An HTTP rejection, with validated Mopé error details when available."""

response: Response | None

def __init__(
self,
message: str,
*,
response: Response | None = None,
code: int | None = None,
data: JsonValue = None,
) -> None:
super().__init__(message, response=response)
self.message = message
self.code = code
self.data = data

@property
def status_code(self) -> int | None:
return self.response.status_code if self.response is not None else None

@classmethod
def from_response(cls, response: Response, *, fallback_message: str) -> Self:
try:
payload = json_object(response.json())
# The schema wraps details in "error"; documented examples are unwrapped.
details = json_object(payload.get("error", payload), path="error")
code = json_integer(details["code"], path="error.code")
message = json_string(details["message"], path="error.message")
except (TypeError, ValueError, KeyError):
return cls(fallback_message, response=response)
return cls(message, response=response, code=code, data=details.get("data"))


def raise_for_status(response: Response) -> None:
"""Preserve HTTPError compatibility without letting a bad error body mask it."""
try:
response.raise_for_status()
except HTTPError as error:
raise MopeAPIError.from_response(
response, fallback_message=str(error)
) from error
5 changes: 3 additions & 2 deletions mope/resources/shop.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from mope.errors import raise_for_status
from mope.models.payments import CreatePaymentResponse, CurrencyCode, PaymentRequest
from mope.transport import ApiTransport

Expand Down Expand Up @@ -30,7 +31,7 @@ def create_payment_request(
"redirect_url": redirect_url,
},
)
response.raise_for_status()
raise_for_status(response)
return CreatePaymentResponse.from_json(response.json())

def get_payment_request(self, payment_id: str) -> PaymentRequest:
Expand All @@ -40,5 +41,5 @@ def get_payment_request(self, payment_id: str) -> PaymentRequest:

endpoint = f"shop/payment_request/{payment_id}"
response = self._client.call_api("GET", endpoint=endpoint)
response.raise_for_status()
raise_for_status(response)
return PaymentRequest.from_json(response.json())
167 changes: 0 additions & 167 deletions tests/test_models.py

This file was deleted.

Loading
Loading