-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathdomain.py
More file actions
133 lines (105 loc) · 3.79 KB
/
domain.py
File metadata and controls
133 lines (105 loc) · 3.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
from __future__ import annotations
from datetime import datetime
from typing import Any, overload
from dateutil.parser import isoparse
class BaseDomain:
__api_properties__: tuple[str, ...]
@classmethod
def from_dict(cls, data: dict[str, Any]): # type: ignore[no-untyped-def]
"""
Build the domain object from the data dict.
"""
supported_data = {k: v for k, v in data.items() if k in cls.__api_properties__}
return cls(**supported_data)
def __repr__(self) -> str:
kwargs = [f"{key}={getattr(self, key)!r}" for key in self.__api_properties__]
return f"{self.__class__.__qualname__}({', '.join(kwargs)})"
def __eq__(self, other: Any) -> bool:
"""Compare a domain object with another of the same type."""
if not isinstance(other, self.__class__):
return NotImplemented
for key in self.__api_properties__:
if getattr(self, key) != getattr(other, key):
return False
return True
@overload
def _parse_datetime(self, value: str) -> datetime: ...
@overload
def _parse_datetime(self, value: None) -> None: ...
def _parse_datetime(self, value: str | None) -> datetime | None:
if value is None:
return None
return isoparse(value)
class DomainIdentityMixin:
id: int | None
name: str | None
@property
def id_or_name(self) -> int | str:
"""
Return the first defined value, and fails if none is defined.
"""
if self.id is not None:
return self.id
if self.name is not None:
return self.name
raise ValueError("id or name must be set")
def has_id_or_name(self, id_or_name: int | str) -> bool:
"""
Return whether this domain has the same id or same name as the other.
The domain calling this method MUST be a bound domain or be populated, otherwise
the comparison will not work as expected (e.g. the domains are the same but
cannot be equal, if one provides an id and the other the name).
"""
result = None
if self.id is not None:
value = id_or_name
if isinstance(id_or_name, str) and id_or_name.isnumeric():
value = int(id_or_name)
result = result or self.id == value
if self.name is not None:
result = result or self.name == str(id_or_name)
if result is None:
raise ValueError("id or name must be set")
return result
class Pagination(BaseDomain):
__api_properties__ = (
"page",
"per_page",
"previous_page",
"next_page",
"last_page",
"total_entries",
)
__slots__ = __api_properties__
def __init__(
self,
page: int,
per_page: int,
previous_page: int | None = None,
next_page: int | None = None,
last_page: int | None = None,
total_entries: int | None = None,
):
self.page = page
self.per_page = per_page
self.previous_page = previous_page
self.next_page = next_page
self.last_page = last_page
self.total_entries = total_entries
class Meta(BaseDomain):
__api_properties__ = ("pagination",)
__slots__ = __api_properties__
def __init__(self, pagination: Pagination | None = None):
self.pagination = pagination
@classmethod
def parse_meta(cls, response: dict[str, Any]) -> Meta:
"""
If present, extract the meta details from the response and return a meta object.
"""
meta = cls()
if response and "meta" in response:
try:
meta.pagination = Pagination(**response["meta"]["pagination"])
except KeyError:
pass
return meta