18 from typing
import Optional, Any, Dict, List
19 from typing_extensions
import Self
23 from .network_manager
import networkManager
24 from .network_response
import NetworkRequestError
25 from ..codable
import Codable
28 DEFAULT_PAGE_SIZE = 100
34 Base class for every Coretex.ai entity representation in Python
41 boolean value that represents if object will be shown or not
48 def __init__(self) -> None:
52 def _endpoint(cls) -> str:
54 Maps the entity endpoint to overriden value, else
55 it uses inflection.underscode on the class name for endpoint
59 str -> Coretex.ai object endpoint for a given class
62 return inflection.underscore(cls.__name__)
66 Maps the entity url to the frontend page url
70 str -> The URL path on Coretex for the entity.
73 return f
"{type(self).__name__.lower()}/{self.id}"
75 def __eq__(self, __o: object) -> bool:
77 Checks if the NetworkObjects which have id property
83 object to which we are comparing self
87 bool -> True if ids are present and equal, False in any other case
91 if isinstance(__o, NetworkObject):
92 return self.
idid == __o.id
98 Calculates hash of the object in a non-randomized manner
102 int -> hash of all the items defined on the self.__dict__ object
105 return hash(tuple(sorted(self.__dict__.items())))
107 def refresh(self, jsonObject: Optional[Dict[str, Any]] =
None) -> bool:
109 Updates objects fields to a provided value if set, otherwise
110 fetches the object from the API and updates the values
111 using the fetched object
115 jsonObject : Optional[Dict[str, Any]]
116 A serialized json object to which the values should be updated, if provided
120 bool -> True if the update was successful, False otherwise
124 if jsonObject
is not None:
131 except NetworkRequestError:
134 for key, value
in obj.__dict__.items():
135 self.__dict__[key] = value
141 Sends a PUT request to Coretex backend
145 **kwargs : Dict[str, Any]
146 parameters which will be sent as request body
150 bool -> True if request was successful, False otherwise
156 endpoint = f
"{self._endpoint()}/{self.id}"
157 return not networkManager.put(endpoint, kwargs).hasFailed()
161 Sends a DELETE request to Coretex backend
165 bool -> True if request was successful, False otherwise
171 endpoint = f
"{self._endpoint()}/{self.id}"
172 return not networkManager.delete(endpoint).hasFailed()
177 Creates the entity linked to this class on Coretex backend
181 **kwargs : Dict[str, Any]
182 parameters which will be sent as request body
186 Self -> created object if request was successful
190 NetworkRequestError -> If the request for creating failed
193 response = networkManager.post(cls.
_endpoint_endpoint(), kwargs)
194 if response.hasFailed():
195 raise NetworkRequestError(response, f
">> [Coretex] Failed to create \"{cls.__name__}\" with parameters \"{kwargs}\"")
197 return cls.
decodedecode(response.getJson(dict))
202 Fetches all entities from Coretex backend which match
207 **kwargs : Optional[Dict[str, Any]]
208 query parameters (predicate) which will be appended to URL
212 List[Self] -> list of all fetched entities
216 NetworkRequestError -> If the request for fetching failed
219 if "page_size" not in kwargs:
220 kwargs[
"page_size"] = DEFAULT_PAGE_SIZE
222 response = networkManager.get(cls.
_endpoint_endpoint(), kwargs)
223 if response.hasFailed():
224 raise NetworkRequestError(response, f
"Failed to fetch \"{cls.__name__}\" with parameters \"{kwargs}\"")
226 objects: List[Self] = []
228 for obj
in response.getJson(list):
229 objects.append(cls.
decodedecode(obj))
236 Fetches one entity from Coretex backend which matches
241 **kwargs : Optional[Dict[str, Any]]
242 query parameters (predicate) which will be appended to URL
246 Self -> fetched entity
250 NetworkRequestError -> If the request for fetching failed
251 ValueError -> If no object was fetched
254 kwargs[
"page_size"] = 1
255 result = cls.
fetchAllfetchAll(**kwargs)
258 raise ValueError(f
"Failed to fetch \"{cls.__name__}\" with parameters \"{kwargs}\"")
263 def fetchById(cls, objectId: int, **kwargs: Any) -> Self:
265 Fetches a single entity with the matching id
270 id of the object which is fetched
271 **kwargs : Optional[Dict[str, Any]]
272 query parameters (predicate) which will be appended to URL
276 Optional[Self] -> fetched object if request was successful, None otherwise
280 NetworkRequestError -> If the request for fetching failed
283 if "page_size" not in kwargs:
284 kwargs[
"page_size"] = DEFAULT_PAGE_SIZE
286 response = networkManager.get(f
"{cls._endpoint()}/{objectId}", kwargs)
288 if response.hasFailed():
289 raise NetworkRequestError(response, f
"Failed to fetch \"{cls.__name__}\" with ID \"{objectId}\"")
291 return cls.
decodedecode(response.getJson(dict))
Self decode(cls, Dict[str, Any] encodedObject)
None _updateFields(self, Dict[str, Any] encodedObject)
Self fetchOne(cls, **Any kwargs)
Self fetchById(cls, int objectId, **Any kwargs)
bool refresh(self, Optional[Dict[str, Any]] jsonObject=None)
bool update(self, **Any kwargs)
bool __eq__(self, object __o)
List[Self] fetchAll(cls, **Any kwargs)
Self create(cls, **Any kwargs)