|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import json |
4 | | -from abc import ABC, abstractmethod |
5 | | -from typing import ( |
6 | | - TYPE_CHECKING, |
7 | | - Any, |
8 | | - AsyncIterator, |
9 | | - Awaitable, |
10 | | - Callable, |
11 | | - Generic, |
12 | | - Mapping, |
13 | | - TypeVar, |
14 | | - cast, |
15 | | -) |
| 4 | +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Protocol, runtime_checkable |
16 | 5 |
|
17 | 6 | from httpx import Response as ClientResponse |
| 7 | +from pydantic import BaseModel, ConfigDict, Field |
18 | 8 |
|
19 | | -from .utils import as_dict, as_params |
| 9 | +from .utils import as_dict |
20 | 10 |
|
21 | 11 | if TYPE_CHECKING: # pragma: no cover |
22 | 12 | from .client import Metablock |
@@ -45,212 +35,33 @@ def __str__(self) -> str: |
45 | 35 | return json.dumps(self.message, indent=4) |
46 | 36 |
|
47 | 37 |
|
48 | | -class HttpComponent(ABC): |
| 38 | +@runtime_checkable |
| 39 | +class HttpComponent(Protocol): |
49 | 40 | @property |
50 | | - @abstractmethod |
51 | 41 | def cli(self) -> Metablock: # pragma: no cover |
52 | 42 | ... |
53 | 43 |
|
54 | 44 | @property |
55 | | - @abstractmethod |
56 | 45 | def url(self) -> str: # pragma: no cover |
57 | 46 | ... |
58 | 47 |
|
59 | | - def __repr__(self) -> str: |
60 | | - return self.url |
61 | | - |
62 | | - def __str__(self) -> str: |
63 | | - return self.__repr__() |
64 | 48 |
|
| 49 | +class MetablockComponent(BaseModel): |
| 50 | + model_config = ConfigDict(arbitrary_types_allowed=True) |
65 | 51 |
|
66 | | -class Component(HttpComponent): |
67 | | - def __init__( |
68 | | - self, root: Metablock | CrudComponent | MetablockEntity, name: str = "" |
69 | | - ) -> None: |
70 | | - self.root = root |
71 | | - self.name = name or self.__class__.__name__.lower() |
| 52 | + root: HttpComponent = Field(exclude=True) |
| 53 | + root_path: str = Field(exclude=True) |
72 | 54 |
|
73 | 55 | @property |
74 | 56 | def cli(self) -> Metablock: |
75 | 57 | return self.root.cli |
76 | 58 |
|
77 | 59 | @property |
78 | 60 | def url(self) -> str: |
79 | | - return f"{self.cli.url}/{self.name}" |
80 | | - |
81 | | - @property |
82 | | - def parent_url(self) -> str: |
83 | | - return f"{self.root.url}/{self.name}" |
84 | | - |
85 | | - @property |
86 | | - def is_entity(self) -> bool: |
87 | | - return isinstance(self.root, MetablockEntity) |
| 61 | + return f"{self.root.url}/{self.root_path}" |
88 | 62 |
|
89 | 63 |
|
90 | | -class MetablockEntity(HttpComponent): |
| 64 | +class MetablockEntity(MetablockComponent): |
91 | 65 | """A Metablock entity""" |
92 | 66 |
|
93 | | - __slots__ = ("root", "data") |
94 | | - |
95 | | - def __init__( |
96 | | - self, |
97 | | - root: Metablock | CrudComponent | MetablockEntity, |
98 | | - data: dict, |
99 | | - ) -> None: |
100 | | - self.root = root |
101 | | - self.data = data |
102 | | - |
103 | | - def __repr__(self) -> str: |
104 | | - return repr(self.data) |
105 | | - |
106 | | - def __getitem__(self, item: str) -> Any: |
107 | | - return self.data[item] |
108 | | - |
109 | | - def __contains__(self, item: str) -> bool: |
110 | | - return item in self.data |
111 | | - |
112 | | - def __eq__(self, other: Any) -> bool: |
113 | | - return isinstance(other, self.__class__) and self.data == other.data |
114 | | - |
115 | | - def _asdict(self) -> dict: |
116 | | - return self.data |
117 | | - |
118 | | - @property |
119 | | - def cli(self) -> Metablock: |
120 | | - return self.root.cli |
121 | | - |
122 | | - @property |
123 | | - def id(self) -> str: |
124 | | - return self.data.get("id", "") |
125 | | - |
126 | | - @property |
127 | | - def name(self) -> str: |
128 | | - return self.data.get("name", "") |
129 | | - |
130 | | - @property |
131 | | - def url(self) -> str: |
132 | | - return "%s/%s" % (self.root.url, self.id) |
133 | | - |
134 | | - def nice(self) -> str: |
135 | | - return json.dumps(self.data, indent=4) |
136 | | - |
137 | | - |
138 | | -E = TypeVar("E", bound="MetablockEntity") |
139 | | - |
140 | | - |
141 | | -class CrudComponent(Component, Generic[E]): |
142 | | - def __init__( |
143 | | - self, |
144 | | - root: Metablock | CrudComponent | MetablockEntity, |
145 | | - factory: type[E], |
146 | | - name: str = "", |
147 | | - ) -> None: |
148 | | - super().__init__(root, name) |
149 | | - self.factory = factory |
150 | | - |
151 | | - async def paginate(self, **params: Any) -> AsyncIterator[E]: |
152 | | - next_ = self.list_create_url() |
153 | | - url_params: Any = as_params(**params) |
154 | | - while next_: |
155 | | - next_, data = await self.cli.request( |
156 | | - next_, params=url_params, callback=self._paginated |
157 | | - ) |
158 | | - url_params = None |
159 | | - for d in data: |
160 | | - yield self.entity(d) |
161 | | - |
162 | | - async def get_list(self, **kwargs: Any) -> list[E]: |
163 | | - url = self.list_create_url() |
164 | | - kwargs.setdefault("wrap", self.entity_list) |
165 | | - return cast( |
166 | | - list[E], |
167 | | - await self.cli.request(url, **kwargs), |
168 | | - ) |
169 | | - |
170 | | - async def get_full_list(self, **kwargs: Any) -> list[E]: |
171 | | - return [d async for d in self.paginate(**kwargs)] |
172 | | - |
173 | | - async def get(self, id_: str, **kwargs: Any) -> E: |
174 | | - url = f"{self.url}/{id_}" |
175 | | - kwargs.setdefault("wrap", self.entity) |
176 | | - return cast(E, await self.cli.get(url, **kwargs)) |
177 | | - |
178 | | - async def has(self, id_: str, **kwargs: Any) -> bool: |
179 | | - url = f"{self.url}/{id_}" |
180 | | - return cast(bool, await self.cli.get(url, callback=self._head)) |
181 | | - |
182 | | - async def create(self, callback: Callback | None = None, **params: Any) -> E: |
183 | | - url = self.list_create_url() |
184 | | - return cast( |
185 | | - E, |
186 | | - await self.cli.post(url, json=params, callback=callback, wrap=self.entity), |
187 | | - ) |
188 | | - |
189 | | - async def update( |
190 | | - self, id_name: str, callback: Callback | None = None, **params: Any |
191 | | - ) -> E: |
192 | | - return cast( |
193 | | - E, |
194 | | - await self.cli.patch( |
195 | | - self.update_url(id_name), |
196 | | - json=params, |
197 | | - callback=callback, |
198 | | - wrap=self.entity, |
199 | | - ), |
200 | | - ) |
201 | | - |
202 | | - async def upsert(self, callback: Callback | None = None, **params: Any) -> E: |
203 | | - return cast( |
204 | | - E, |
205 | | - await self.cli.put( |
206 | | - self.url, json=params, callback=callback, wrap=self.entity |
207 | | - ), |
208 | | - ) |
209 | | - |
210 | | - async def delete( # type: ignore |
211 | | - self, |
212 | | - id_name: str, |
213 | | - **kwargs: Any, |
214 | | - ) -> Any: |
215 | | - return await self.cli.delete(self.delete_url(id_name), **kwargs) |
216 | | - |
217 | | - async def delete_all(self) -> int: |
218 | | - n = 0 |
219 | | - async for entity in self.paginate(): |
220 | | - await self.delete(entity.id) |
221 | | - n += 1 |
222 | | - return n |
223 | | - |
224 | | - def entity(self, data: dict) -> E: |
225 | | - return self.factory(self, data) |
226 | | - |
227 | | - def entity_list(self, data: list[dict]) -> list[E]: |
228 | | - return [self.entity(d) for d in data] |
229 | | - |
230 | | - def list_create_url(self) -> str: |
231 | | - return self.parent_url if self.is_entity else self.url |
232 | | - |
233 | | - def update_url(self, id_name: str) -> str: |
234 | | - return f"{self.url}/{id_name}" |
235 | | - |
236 | | - def delete_url(self, id_name: str) -> str: |
237 | | - return f"{self.url}/{id_name}" |
238 | | - |
239 | | - # callbacks |
240 | | - |
241 | | - async def _head(self, response: ClientResponse) -> bool: |
242 | | - if response.status_code == 404: |
243 | | - return False |
244 | | - elif response.status_code == 200: |
245 | | - return True |
246 | | - else: # pragma: no cover |
247 | | - raise MetablockResponseError(response) |
248 | | - |
249 | | - async def _paginated(self, response: ClientResponse) -> Any: |
250 | | - next_ = response.links.get("next") |
251 | | - if isinstance(next_, Mapping): |
252 | | - url = next_.get("url") |
253 | | - else: |
254 | | - url = None |
255 | | - data = await self.cli.handle_response(response) |
256 | | - return (url, data) |
| 67 | + id: str = Field(description="The unique identifier of the entity") |
0 commit comments