python-mope 0.1.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. python_mope-0.3.1/LICENSE +21 -0
  2. python_mope-0.3.1/PKG-INFO +136 -0
  3. python_mope-0.3.1/README.md +110 -0
  4. {python-mope-0.1.0 → python_mope-0.3.1}/mope/__version__.py +1 -1
  5. python_mope-0.3.1/mope/client.py +110 -0
  6. python_mope-0.3.1/mope/errors.py +52 -0
  7. python_mope-0.3.1/mope/json.py +49 -0
  8. python_mope-0.3.1/mope/models/payments.py +110 -0
  9. python_mope-0.3.1/mope/resources/__init__.py +0 -0
  10. {python-mope-0.1.0 → python_mope-0.3.1}/mope/resources/shop.py +8 -6
  11. python_mope-0.3.1/mope/transport.py +11 -0
  12. python_mope-0.3.1/pyproject.toml +73 -0
  13. python_mope-0.3.1/python_mope.egg-info/PKG-INFO +136 -0
  14. {python-mope-0.1.0 → python_mope-0.3.1}/python_mope.egg-info/SOURCES.txt +6 -2
  15. python_mope-0.3.1/python_mope.egg-info/requires.txt +1 -0
  16. python_mope-0.3.1/tests/test_mope.py +204 -0
  17. python-mope-0.1.0/PKG-INFO +0 -79
  18. python-mope-0.1.0/README.md +0 -55
  19. python-mope-0.1.0/mope/client.py +0 -50
  20. python-mope-0.1.0/mope/models/payments.py +0 -63
  21. python-mope-0.1.0/python_mope.egg-info/PKG-INFO +0 -79
  22. python-mope-0.1.0/python_mope.egg-info/requires.txt +0 -1
  23. python-mope-0.1.0/python_mope.egg-info/zip-safe +0 -1
  24. python-mope-0.1.0/setup.py +0 -41
  25. python-mope-0.1.0/tests/test_mope.py +0 -88
  26. {python-mope-0.1.0 → python_mope-0.3.1}/mope/__init__.py +0 -0
  27. {python-mope-0.1.0 → python_mope-0.3.1}/mope/models/__init__.py +0 -0
  28. /python-mope-0.1.0/mope/resources/__init__.py → /python_mope-0.3.1/mope/py.typed +0 -0
  29. {python-mope-0.1.0 → python_mope-0.3.1}/python_mope.egg-info/dependency_links.txt +0 -0
  30. {python-mope-0.1.0 → python_mope-0.3.1}/python_mope.egg-info/top_level.txt +0 -0
  31. {python-mope-0.1.0 → python_mope-0.3.1}/setup.cfg +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Lemuel Boyce
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-mope
3
+ Version: 0.3.1
4
+ Summary: A client library for interacting with the Mopé Web Shop API
5
+ Author-email: Lemuel Boyce <lemuel@vokality.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/rhymiz/python-mope
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Development Status :: 6 - Mature
17
+ Classifier: Environment :: Web Environment
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Topic :: Office/Business :: Financial
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: requests<3,>=2.34.2
25
+ Dynamic: license-file
26
+
27
+ ![build](https://github.com/rhymiz/python-mope/workflows/build/badge.svg)
28
+ [![downloads](https://pepy.tech/badge/python-mope)](https://pepy.tech/project/python-mope)
29
+ [![Ruff](https://img.shields.io/badge/lint%20and%20format-Ruff-D7FF64.svg)](https://docs.astral.sh/ruff/)
30
+
31
+ # Python Mopé
32
+ Client library for Mopé by Hakrinbank
33
+
34
+ ### Token acquisition and API Docs
35
+ - [API Docs](https://api.mope.sr/integration/doc)
36
+ - Instructions for [acquiring a token](https://drive.google.com/file/d/10fWqgpl2Ip9JIacl0pwzUDi_HV6WLbCi/view?usp=sharing)
37
+
38
+
39
+ ### Requirements
40
+ - Python 3.11 or newer
41
+ - Mopé API Token
42
+
43
+ ### Getting Started
44
+ First, install from PyPi by running `pip install python-mope`
45
+
46
+ Example usage:
47
+
48
+ ```python
49
+ from mope import Mope
50
+
51
+ mope = Mope(token="test_123")
52
+ mope.shop.get_payment_request(payment_id="123")
53
+ ```
54
+
55
+ ### Timeouts and errors
56
+
57
+ Requests use a 5-second connect timeout and a 30-second read timeout by default.
58
+ Configure both with `Mope(token="test_123", timeout=(3.0, 15.0))`, or pass a
59
+ single number of seconds to apply to both. `mope.client.Client` accepts the same
60
+ keyword argument. Values must be finite and greater than zero. The read timeout
61
+ limits inactivity between received bytes, not the total duration of a request.
62
+
63
+ Shop methods raise `mope.errors.MopeAPIError` for HTTP errors. It is a subclass
64
+ of `requests.HTTPError`, so existing handlers keep working. Its `status_code`,
65
+ `code`, `message`, and `data` fields expose the HTTP status and validated Mopé
66
+ error details, such as code `1033` for account limits exceeded. If the error body
67
+ is missing or malformed, `code` and `data` are `None` and `message` retains the
68
+ HTTP error description. The original response and exception cause are preserved.
69
+
70
+ Connection failures and timeouts remain `requests.RequestException` subclasses.
71
+ Malformed successful responses still raise `TypeError`, `ValueError`, or
72
+ `KeyError`; invalid JSON raises `requests.exceptions.JSONDecodeError`, which is
73
+ also a `ValueError`. Applications should translate these errors at the API call
74
+ boundary and decide which failures are retryable. Requests are not automatically
75
+ retried, including payment creation after a timeout.
76
+
77
+ ### Development
78
+
79
+ Install [uv](https://docs.astral.sh/uv/getting-started/installation/), then run:
80
+
81
+ ```sh
82
+ uv sync --locked
83
+ uv run --locked ruff check .
84
+ uv run --locked ruff format --check .
85
+ uv run --locked ty check
86
+ uv run --locked pytest
87
+ uv build --no-sources
88
+ ```
89
+
90
+ Development uses Python 3.15.2 from `.python-version`; uv installs it when needed.
91
+ The library supports Python 3.11+, and CI tests the built wheel on Python 3.11,
92
+ 3.12, 3.13, 3.14, and 3.15. Ruff and ty target Python 3.11 compatibility.
93
+ Run `uv run ruff format .` to format code. Commit `uv.lock` after changing
94
+ dependencies; use `uv lock --upgrade` to refresh their locked versions.
95
+
96
+ The package includes inline types and a `py.typed` marker. API responses are
97
+ validated before creating models: invalid field types raise `TypeError`, invalid
98
+ status values raise `ValueError`, and missing required fields raise `KeyError`.
99
+ Values are not coerced. Payment metadata remains a list of dictionaries with
100
+ string `key` and `value` fields, as defined by the
101
+ [Mopé API schema](https://api.mope.sr/integration/paths/GetPaymentRequest.yaml).
102
+
103
+ ### Publishing
104
+
105
+ To release, update `mope/__version__.py`, run `uv lock`, and commit the changes.
106
+ Publish a GitHub release whose tag is the package version or `v` followed by that
107
+ version. The workflow checks the tag, runs lint, formatting and type checks,
108
+ builds the source distribution and wheel, and tests the installed wheel across
109
+ all supported Python versions before uploading those same artifacts to PyPI.
110
+
111
+ ### Resources
112
+ #### shop
113
+
114
+ *Methods*
115
+
116
+ ##### `shop.create_payment_request`
117
+
118
+ | Argument | Type | Required |
119
+ | --- |--- | --- |
120
+ |amount | int | yes |
121
+ |description | string | yes |
122
+ |order_id | string | yes |
123
+ |currency | enum (USD, SRD, EUR) | yes |
124
+ |redirect_url| string | yes |
125
+
126
+
127
+ return type: `mope.models.payments.CreatePaymentResponse`
128
+
129
+ ##### `shop.get_payment_request`
130
+
131
+ | Argument | Type | Required |
132
+ |--- |--- |--- |
133
+ |payment_id | string | yes |
134
+
135
+
136
+ return type: `mope.models.payments.PaymentRequest`
@@ -0,0 +1,110 @@
1
+ ![build](https://github.com/rhymiz/python-mope/workflows/build/badge.svg)
2
+ [![downloads](https://pepy.tech/badge/python-mope)](https://pepy.tech/project/python-mope)
3
+ [![Ruff](https://img.shields.io/badge/lint%20and%20format-Ruff-D7FF64.svg)](https://docs.astral.sh/ruff/)
4
+
5
+ # Python Mopé
6
+ Client library for Mopé by Hakrinbank
7
+
8
+ ### Token acquisition and API Docs
9
+ - [API Docs](https://api.mope.sr/integration/doc)
10
+ - Instructions for [acquiring a token](https://drive.google.com/file/d/10fWqgpl2Ip9JIacl0pwzUDi_HV6WLbCi/view?usp=sharing)
11
+
12
+
13
+ ### Requirements
14
+ - Python 3.11 or newer
15
+ - Mopé API Token
16
+
17
+ ### Getting Started
18
+ First, install from PyPi by running `pip install python-mope`
19
+
20
+ Example usage:
21
+
22
+ ```python
23
+ from mope import Mope
24
+
25
+ mope = Mope(token="test_123")
26
+ mope.shop.get_payment_request(payment_id="123")
27
+ ```
28
+
29
+ ### Timeouts and errors
30
+
31
+ Requests use a 5-second connect timeout and a 30-second read timeout by default.
32
+ Configure both with `Mope(token="test_123", timeout=(3.0, 15.0))`, or pass a
33
+ single number of seconds to apply to both. `mope.client.Client` accepts the same
34
+ keyword argument. Values must be finite and greater than zero. The read timeout
35
+ limits inactivity between received bytes, not the total duration of a request.
36
+
37
+ Shop methods raise `mope.errors.MopeAPIError` for HTTP errors. It is a subclass
38
+ of `requests.HTTPError`, so existing handlers keep working. Its `status_code`,
39
+ `code`, `message`, and `data` fields expose the HTTP status and validated Mopé
40
+ error details, such as code `1033` for account limits exceeded. If the error body
41
+ is missing or malformed, `code` and `data` are `None` and `message` retains the
42
+ HTTP error description. The original response and exception cause are preserved.
43
+
44
+ Connection failures and timeouts remain `requests.RequestException` subclasses.
45
+ Malformed successful responses still raise `TypeError`, `ValueError`, or
46
+ `KeyError`; invalid JSON raises `requests.exceptions.JSONDecodeError`, which is
47
+ also a `ValueError`. Applications should translate these errors at the API call
48
+ boundary and decide which failures are retryable. Requests are not automatically
49
+ retried, including payment creation after a timeout.
50
+
51
+ ### Development
52
+
53
+ Install [uv](https://docs.astral.sh/uv/getting-started/installation/), then run:
54
+
55
+ ```sh
56
+ uv sync --locked
57
+ uv run --locked ruff check .
58
+ uv run --locked ruff format --check .
59
+ uv run --locked ty check
60
+ uv run --locked pytest
61
+ uv build --no-sources
62
+ ```
63
+
64
+ Development uses Python 3.15.2 from `.python-version`; uv installs it when needed.
65
+ The library supports Python 3.11+, and CI tests the built wheel on Python 3.11,
66
+ 3.12, 3.13, 3.14, and 3.15. Ruff and ty target Python 3.11 compatibility.
67
+ Run `uv run ruff format .` to format code. Commit `uv.lock` after changing
68
+ dependencies; use `uv lock --upgrade` to refresh their locked versions.
69
+
70
+ The package includes inline types and a `py.typed` marker. API responses are
71
+ validated before creating models: invalid field types raise `TypeError`, invalid
72
+ status values raise `ValueError`, and missing required fields raise `KeyError`.
73
+ Values are not coerced. Payment metadata remains a list of dictionaries with
74
+ string `key` and `value` fields, as defined by the
75
+ [Mopé API schema](https://api.mope.sr/integration/paths/GetPaymentRequest.yaml).
76
+
77
+ ### Publishing
78
+
79
+ To release, update `mope/__version__.py`, run `uv lock`, and commit the changes.
80
+ Publish a GitHub release whose tag is the package version or `v` followed by that
81
+ version. The workflow checks the tag, runs lint, formatting and type checks,
82
+ builds the source distribution and wheel, and tests the installed wheel across
83
+ all supported Python versions before uploading those same artifacts to PyPI.
84
+
85
+ ### Resources
86
+ #### shop
87
+
88
+ *Methods*
89
+
90
+ ##### `shop.create_payment_request`
91
+
92
+ | Argument | Type | Required |
93
+ | --- |--- | --- |
94
+ |amount | int | yes |
95
+ |description | string | yes |
96
+ |order_id | string | yes |
97
+ |currency | enum (USD, SRD, EUR) | yes |
98
+ |redirect_url| string | yes |
99
+
100
+
101
+ return type: `mope.models.payments.CreatePaymentResponse`
102
+
103
+ ##### `shop.get_payment_request`
104
+
105
+ | Argument | Type | Required |
106
+ |--- |--- |--- |
107
+ |payment_id | string | yes |
108
+
109
+
110
+ return type: `mope.models.payments.PaymentRequest`
@@ -1,2 +1,2 @@
1
1
  __author__ = "lemuel@vokality.com"
2
- __version__ = "0.1.0"
2
+ __version__ = "0.3.1"
@@ -0,0 +1,110 @@
1
+ from collections.abc import Iterable, Mapping, Set
2
+ from math import isfinite
3
+ from typing import IO, Protocol, TypeAlias
4
+ from urllib.parse import urljoin
5
+
6
+ import requests
7
+
8
+ from mope.__version__ import __version__
9
+ from mope.json import json_value
10
+ from mope.resources.shop import ShopResource
11
+
12
+ QueryScalar: TypeAlias = str | bytes | int | float
13
+ QueryValue: TypeAlias = QueryScalar | Iterable[QueryScalar] | None
14
+
15
+
16
+ class QueryItems(Protocol):
17
+ def items(self) -> Set[tuple[QueryScalar, QueryValue]]: ...
18
+
19
+
20
+ QueryParams: TypeAlias = (
21
+ QueryItems | Iterable[tuple[QueryScalar, QueryValue]] | str | bytes
22
+ )
23
+ RequestData: TypeAlias = (
24
+ Mapping[str, object]
25
+ | list[tuple[str, object]]
26
+ | tuple[tuple[str, object], ...]
27
+ | Iterable[bytes]
28
+ | IO[str]
29
+ | IO[bytes]
30
+ | str
31
+ | bytes
32
+ )
33
+ RequestTimeout: TypeAlias = float | tuple[float, float]
34
+
35
+ _user_agent = f"Python Mope {__version__}"
36
+ _BASE_URL = "https://api.mope.sr/api/"
37
+ _DEFAULT_TIMEOUT = (5.0, 30.0)
38
+
39
+
40
+ def _timeout_seconds(value: object) -> float:
41
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
42
+ raise TypeError("timeout must contain numbers of seconds")
43
+ try:
44
+ seconds = float(value)
45
+ except OverflowError as error:
46
+ raise ValueError("timeout must be finite and greater than zero") from error
47
+ if not isfinite(seconds) or seconds <= 0:
48
+ raise ValueError("timeout must be finite and greater than zero")
49
+ return seconds
50
+
51
+
52
+ def _request_timeout(value: object) -> RequestTimeout:
53
+ if isinstance(value, tuple):
54
+ if len(value) != 2:
55
+ raise ValueError("timeout must be a (connect, read) pair")
56
+ return (_timeout_seconds(value[0]), _timeout_seconds(value[1]))
57
+ return _timeout_seconds(value)
58
+
59
+
60
+ class Client:
61
+ def __init__(
62
+ self, token: str, *, timeout: RequestTimeout = _DEFAULT_TIMEOUT
63
+ ) -> None:
64
+ self._timeout = _request_timeout(timeout)
65
+ self._token = token
66
+ self._headers = {
67
+ "User-Agent": _user_agent,
68
+ "Content-Type": "application/json",
69
+ "Authorization": f"Bearer {token}",
70
+ }
71
+ self._base_url = _BASE_URL
72
+
73
+ def call_api(
74
+ self,
75
+ method: str,
76
+ endpoint: str,
77
+ params: QueryParams | None = None,
78
+ data: RequestData | None = None,
79
+ json: object = None,
80
+ ) -> requests.Response:
81
+ url = urljoin(self._base_url, endpoint)
82
+ return requests.request(
83
+ method=method,
84
+ url=url,
85
+ params=params,
86
+ data=data,
87
+ json=json_value(json, path="request"),
88
+ headers=self._headers,
89
+ timeout=self._timeout,
90
+ )
91
+
92
+
93
+ class Mope:
94
+ def __init__(
95
+ self, token: str, *, timeout: RequestTimeout = _DEFAULT_TIMEOUT
96
+ ) -> None:
97
+ self._token = token
98
+ self._headers = {
99
+ "User-Agent": _user_agent,
100
+ "Content-Type": "application/json",
101
+ "Authorization": f"Bearer {token}",
102
+ }
103
+ self.base_url = _BASE_URL
104
+
105
+ self._client = Client(token, timeout=timeout)
106
+
107
+ self.shop = ShopResource(self._client)
108
+
109
+ def __str__(self) -> str:
110
+ return _user_agent
@@ -0,0 +1,52 @@
1
+ """Typed details for HTTP errors returned by the Mopé API."""
2
+
3
+ from typing import Self
4
+
5
+ from requests import HTTPError, Response
6
+
7
+ from mope.json import JsonValue, json_integer, json_object, json_string
8
+
9
+
10
+ class MopeAPIError(HTTPError):
11
+ """An HTTP rejection, with validated Mopé error details when available."""
12
+
13
+ response: Response | None
14
+
15
+ def __init__(
16
+ self,
17
+ message: str,
18
+ *,
19
+ response: Response | None = None,
20
+ code: int | None = None,
21
+ data: JsonValue = None,
22
+ ) -> None:
23
+ super().__init__(message, response=response)
24
+ self.message = message
25
+ self.code = code
26
+ self.data = data
27
+
28
+ @property
29
+ def status_code(self) -> int | None:
30
+ return self.response.status_code if self.response is not None else None
31
+
32
+ @classmethod
33
+ def from_response(cls, response: Response, *, fallback_message: str) -> Self:
34
+ try:
35
+ payload = json_object(response.json())
36
+ # The schema wraps details in "error"; documented examples are unwrapped.
37
+ details = json_object(payload.get("error", payload), path="error")
38
+ code = json_integer(details["code"], path="error.code")
39
+ message = json_string(details["message"], path="error.message")
40
+ except (TypeError, ValueError, KeyError):
41
+ return cls(fallback_message, response=response)
42
+ return cls(message, response=response, code=code, data=details.get("data"))
43
+
44
+
45
+ def raise_for_status(response: Response) -> None:
46
+ """Preserve HTTPError compatibility without letting a bad error body mask it."""
47
+ try:
48
+ response.raise_for_status()
49
+ except HTTPError as error:
50
+ raise MopeAPIError.from_response(
51
+ response, fallback_message=str(error)
52
+ ) from error
@@ -0,0 +1,49 @@
1
+ """JSON types and validation at the API boundary."""
2
+
3
+ from math import isfinite
4
+ from typing import TypeAlias
5
+
6
+ JsonValue: TypeAlias = (
7
+ str | int | float | bool | None | list["JsonValue"] | dict[str, "JsonValue"]
8
+ )
9
+ JsonObject: TypeAlias = dict[str, JsonValue]
10
+
11
+
12
+ def json_value(value: object, *, path: str = "response") -> JsonValue:
13
+ if value is None or isinstance(value, (str, bool, int)):
14
+ return value
15
+ if isinstance(value, float):
16
+ if not isfinite(value):
17
+ raise ValueError(f"{path} must contain a finite JSON number")
18
+ return value
19
+ if isinstance(value, list):
20
+ return [
21
+ json_value(item, path=f"{path}[{index}]")
22
+ for index, item in enumerate(value)
23
+ ]
24
+ if isinstance(value, dict):
25
+ return json_object(value, path=path)
26
+ raise TypeError(f"{path} must be a JSON value")
27
+
28
+
29
+ def json_object(value: object, *, path: str = "response") -> JsonObject:
30
+ if not isinstance(value, dict):
31
+ raise TypeError(f"{path} must be a JSON object")
32
+ result: JsonObject = {}
33
+ for key, item in value.items():
34
+ if not isinstance(key, str):
35
+ raise TypeError(f"{path} must have string keys")
36
+ result[key] = json_value(item, path=f"{path}.{key}")
37
+ return result
38
+
39
+
40
+ def json_string(value: object, *, path: str) -> str:
41
+ if not isinstance(value, str):
42
+ raise TypeError(f"{path} must be a string")
43
+ return value
44
+
45
+
46
+ def json_integer(value: object, *, path: str) -> int:
47
+ if isinstance(value, bool) or not isinstance(value, int):
48
+ raise TypeError(f"{path} must be an integer")
49
+ return value
@@ -0,0 +1,110 @@
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import asdict, dataclass
3
+ from typing import Literal, Self, TypeAlias, TypedDict
4
+
5
+ from mope.json import JsonValue, json_integer, json_object, json_string
6
+
7
+ CurrencyCode: TypeAlias = Literal["SRD", "EUR", "USD"]
8
+ PaymentStatus: TypeAlias = Literal["open", "scanned", "unconfirmed", "paid"]
9
+
10
+
11
+ class PaymentMetadata(TypedDict):
12
+ key: str
13
+ value: str
14
+
15
+
16
+ def _payment_status(value: object) -> PaymentStatus:
17
+ match value:
18
+ case "open":
19
+ return "open"
20
+ case "scanned":
21
+ return "scanned"
22
+ case "unconfirmed":
23
+ return "unconfirmed"
24
+ case "paid":
25
+ return "paid"
26
+ case _:
27
+ raise ValueError("status must be open, scanned, unconfirmed, or paid")
28
+
29
+
30
+ def _payment_metadata(value: object) -> list[PaymentMetadata]:
31
+ if not isinstance(value, list):
32
+ raise TypeError("meta_data must be an array")
33
+ result: list[PaymentMetadata] = []
34
+ for index, entry in enumerate(value):
35
+ path = f"meta_data[{index}]"
36
+ item = json_object(entry, path=path)
37
+ result.append(
38
+ PaymentMetadata(
39
+ key=json_string(item["key"], path=f"{path}.key"),
40
+ value=json_string(item["value"], path=f"{path}.value"),
41
+ )
42
+ )
43
+ return result
44
+
45
+
46
+ @dataclass
47
+ class BaseModel(ABC):
48
+ @classmethod
49
+ @abstractmethod
50
+ def from_json(cls, data: object) -> Self:
51
+ pass
52
+
53
+ def as_dict(self) -> dict[str, JsonValue]:
54
+ return json_object(asdict(self))
55
+
56
+
57
+ @dataclass
58
+ class CreatePaymentResponse(BaseModel):
59
+ id: str
60
+ url: str
61
+
62
+ @classmethod
63
+ def from_json(cls, data: object) -> Self:
64
+ payload = json_object(data)
65
+ return cls(
66
+ id=json_string(payload["id"], path="id"),
67
+ url=json_string(payload["url"], path="url"),
68
+ )
69
+
70
+
71
+ @dataclass
72
+ class Currency(BaseModel):
73
+ name: str
74
+ code: str
75
+ symbol: str
76
+
77
+ @classmethod
78
+ def from_json(cls, data: object) -> Self:
79
+ payload = json_object(data, path="currency")
80
+ return cls(
81
+ name=json_string(payload["name"], path="currency.name"),
82
+ code=json_string(payload["code"], path="currency.code"),
83
+ symbol=json_string(payload["symbol"], path="currency.symbol"),
84
+ )
85
+
86
+
87
+ @dataclass
88
+ class PaymentRequest(BaseModel):
89
+ id: str
90
+ amount: int
91
+ created_at: str
92
+ description: str
93
+ expires_at: str
94
+ currency: Currency
95
+ status: PaymentStatus
96
+ meta_data: list[PaymentMetadata]
97
+
98
+ @classmethod
99
+ def from_json(cls, data: object) -> Self:
100
+ payload = json_object(data)
101
+ return cls(
102
+ id=json_string(payload["id"], path="id"),
103
+ amount=json_integer(payload["amount"], path="amount"),
104
+ created_at=json_string(payload["created_at"], path="created_at"),
105
+ description=json_string(payload["description"], path="description"),
106
+ expires_at=json_string(payload["expires_at"], path="expires_at"),
107
+ currency=Currency.from_json(payload["currency"]),
108
+ status=_payment_status(payload["status"]),
109
+ meta_data=_payment_metadata(payload["meta_data"]),
110
+ )
File without changes
@@ -1,8 +1,10 @@
1
- from mope.models.payments import CreatePaymentResponse, PaymentRequest
1
+ from mope.errors import raise_for_status
2
+ from mope.models.payments import CreatePaymentResponse, CurrencyCode, PaymentRequest
3
+ from mope.transport import ApiTransport
2
4
 
3
5
 
4
6
  class ShopResource:
5
- def __init__(self, client) -> None:
7
+ def __init__(self, client: ApiTransport) -> None:
6
8
  self._client = client
7
9
 
8
10
  def create_payment_request(
@@ -10,7 +12,7 @@ class ShopResource:
10
12
  amount: int,
11
13
  description: str,
12
14
  order_id: str,
13
- currency: str,
15
+ currency: CurrencyCode,
14
16
  redirect_url: str,
15
17
  ) -> CreatePaymentResponse:
16
18
  """
@@ -29,7 +31,7 @@ class ShopResource:
29
31
  "redirect_url": redirect_url,
30
32
  },
31
33
  )
32
- response.raise_for_status()
34
+ raise_for_status(response)
33
35
  return CreatePaymentResponse.from_json(response.json())
34
36
 
35
37
  def get_payment_request(self, payment_id: str) -> PaymentRequest:
@@ -37,7 +39,7 @@ class ShopResource:
37
39
  fetches a payment request given a payment ID
38
40
  """
39
41
 
40
- endpoint = "shop/payment_request/%s" % payment_id
42
+ endpoint = f"shop/payment_request/{payment_id}"
41
43
  response = self._client.call_api("GET", endpoint=endpoint)
42
- response.raise_for_status()
44
+ raise_for_status(response)
43
45
  return PaymentRequest.from_json(response.json())
@@ -0,0 +1,11 @@
1
+ from typing import Protocol
2
+
3
+ from requests import Response
4
+
5
+
6
+ class ApiTransport(Protocol):
7
+ """The HTTP operations required by API resources."""
8
+
9
+ def call_api(
10
+ self, method: str, endpoint: str, *, json: object = None
11
+ ) -> Response: ...