AAS HTTP Client Documentation
Loading...
Searching...
No Matches
sm_registry_implementation.py
Go to the documentation of this file.
1"""Submodel Registry Implementation Module."""
2
3import json
4import logging
5from typing import TYPE_CHECKING
6
7import requests
8from pydantic import BaseModel
9
10if TYPE_CHECKING:
11 from aas_http_client.classes.client.aas_client import AasHttpClient
12
13
14from aas_http_client.utilities.constants import LogIntensity
15from aas_http_client.utilities.encoder import encode_base_64
17 STATUS_CODE_200,
18 STATUS_CODE_201,
19 STATUS_CODE_204,
20 STATUS_CODE_404,
21 log_response,
22)
23
24_logger = logging.getLogger(__name__)
25
26
28 """Implementation of Submodel Registry related API calls."""
29
30 def __init__(self, client: "AasHttpClient"):
31 """Initializes the SubmodelRegistryImplementation with the given client."""
32 self._client = client
33
34 session = client.get_session()
35 if session is None:
36 raise ValueError(
37 "HTTP session is not initialized in the client. Call 'initialize()' method of the client before creating SubmodelRegistryImplementation instance."
38 )
39
40 self._session: requests.Session = session
41
42 # GET /submodel-descriptors/{submodelIdentifier}
43 def get_submodel_descriptor_by_id(self, submodel_identifier: str) -> dict | None:
44 """Returns the Submodel Descriptor for the given submodel identifier.
45
46 :param submodel_identifier: The unique identifier of the Submodel Descriptor
47 :return: Submodel Descriptor data or None if an error occurred
48 """
49 if not self._client.encoded_ids:
50 submodel_identifier = encode_base_64(submodel_identifier)
52 url = f"{self._client.base_url}/submodel-descriptors/{submodel_identifier}"
53
54 self._client.set_token()
55
56 try:
57 response = self._session.get(url, timeout=self._client.time_out)
58 _logger.debug(f"Call REST API url '{response.url}'")
59
60 if response.status_code == STATUS_CODE_404:
61 if self._client.get_log_intensity() == LogIntensity.HIGH:
62 _logger.warning(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
63 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
64 _logger.debug(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
65
66 return None
67
68 if response.status_code != STATUS_CODE_200:
69 log_response(response)
70 return None
71
72 except requests.exceptions.RequestException as e:
73 _logger.error(f"Error call REST API: {e}")
74 return None
75
76 content = response.content.decode("utf-8")
77 return json.loads(content)
78
79 # PUT /submodel-descriptors/{submodelIdentifier}
80 def put_submodel_descriptor_by_id(self, submodel_identifier: str, request_body: dict) -> bool:
81 """Creates or updates an existing Submodel Descriptor.
82
83 :param submodel_identifier: The unique identifier of the Submodel Descriptor
84 :param request_body: Submodel Descriptor object
85 :return: Updated Submodel Descriptor data or None if an error occurred
86 """
87 if not self._client.encoded_ids:
88 submodel_identifier = encode_base_64(submodel_identifier)
90 url = f"{self._client.base_url}/submodel-descriptors/{submodel_identifier}"
91
92 self._client.set_token()
93
94 try:
95 response = self._session.put(url, json=request_body, timeout=self._client.time_out)
96 _logger.debug(f"Call REST API url '{response.url}'")
97
98 if response.status_code == STATUS_CODE_404:
99 if self._client.get_log_intensity() == LogIntensity.HIGH:
100 _logger.warning(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
101 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
102 _logger.debug(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
103
104 return False
105
106 if response.status_code != STATUS_CODE_204:
107 log_response(response)
108 return False
109
110 except requests.exceptions.RequestException as e:
111 _logger.error(f"Error call REST API: {e}")
112 return False
113
114 return True
115
116 # DELETE /submodel-descriptors/{submodelIdentifier}
117 def delete_submodel_descriptor_by_id(self, submodel_identifier: str) -> bool:
118 """Deletes a Submodel Descriptor, i.e. de-registers a submodel.
119
120 :param submodel_identifier: The unique identifier of the Submodel Descriptor
121 :return: True if deletion was successful, False otherwise
122 """
123 if not self._client.encoded_ids:
124 submodel_identifier = encode_base_64(submodel_identifier)
126 url = f"{self._client.base_url}/submodel-descriptors/{submodel_identifier}"
127
128 self._client.set_token()
129
130 try:
131 response = self._session.delete(url, timeout=self._client.time_out)
132 _logger.debug(f"Call REST API url '{response.url}'")
133
134 if response.status_code == STATUS_CODE_404:
135 if self._client.get_log_intensity() == LogIntensity.HIGH:
136 _logger.warning(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
137 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
138 _logger.debug(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
139
140 return False
141
142 if response.status_code != STATUS_CODE_204:
143 log_response(response)
144 return False
145
146 except requests.exceptions.RequestException as e:
147 _logger.error(f"Error call REST API: {e}")
148 return False
149
150 return True
151
152 # GET /submodel-descriptors
153 def get_all_submodel_descriptors(self, limit: int = 100, cursor: str = "") -> dict | None:
154 """Returns all Submodel Descriptors.
155
156 :param limit: The maximum number of elements in the response array
157 :param cursor: A server-generated identifier retrieved from pagingMetadata that specifies from which position the result listing should continue
158 :return: Submodel Descriptors data or None if an error occurred
159 """
160 url = f"{self._client.base_url}/submodel-descriptors"
161
162 params: dict[str, str] = {}
163 if limit:
164 params["limit"] = str(limit)
165 if cursor:
166 params["cursor"] = cursor
167
168 self._client.set_token()
169
170 try:
171 response = self._session.get(url, params=params, timeout=self._client.time_out)
172 _logger.debug(f"Call REST API url '{response.url}'")
173
174 if response.status_code != STATUS_CODE_200:
175 log_response(response)
176 return None
177
178 except requests.exceptions.RequestException as e:
179 _logger.error(f"Error call REST API: {e}")
180 return None
181
182 content = response.content.decode("utf-8")
183 return json.loads(content)
184
185 # POST /submodel-descriptors
186 def post_submodel_descriptor(self, request_body: dict) -> dict | None:
187 """Creates a new Submodel Descriptor, i.e. registers a submodel.
188
189 :param request_body: Submodel Descriptor object
190 :return: Created Submodel Descriptor data or None if an error occurred
191 """
192 url = f"{self._client.base_url}/submodel-descriptors"
193
194 self._client.set_token()
195
196 try:
197 response = self._session.post(url, json=request_body, timeout=self._client.time_out)
198 _logger.debug(f"Call REST API url '{response.url}'")
199
200 if response.status_code != STATUS_CODE_201:
201 log_response(response)
202 return None
203
204 except requests.exceptions.RequestException as e:
205 _logger.error(f"Error call REST API: {e}")
206 return None
207
208 content = response.content.decode("utf-8")
209 return json.loads(content)
210
211 # DELETE /submodel-descriptors
212 def delete_all_submodel_descriptors(self) -> bool:
213 """Deletes all Submodel Descriptors.
214
215 :return: True if deletion was successful, False otherwise
216 """
217 url = f"{self._client.base_url}/submodel-descriptors"
218
219 self._client.set_token()
220
221 try:
222 response = self._session.delete(url, timeout=self._client.time_out)
223 _logger.debug(f"Call REST API url '{response.url}'")
224
225 if response.status_code != STATUS_CODE_204:
226 log_response(response)
227 return False
228
229 except requests.exceptions.RequestException as e:
230 _logger.error(f"Error call REST API: {e}")
231 return False
232
233 return True
234
235 # GET /description
236 def get_self_description(self) -> dict | None:
237 """Returns the self-describing information of a network resource (ServiceDescription).
238
239 :return: self-describing information of a network resource
240 """
241 url = f"{self._client.base_url}/description"
242
243 self._client.set_token()
244
245 try:
246 response = self._session.get(url, timeout=self._client.time_out)
247 _logger.debug(f"Call REST API url '{response.url}'")
248
249 if response.status_code != STATUS_CODE_200:
250 log_response(response)
251 return None
252
253 except requests.exceptions.RequestException as e:
254 _logger.error(f"Error call REST API: {e}")
255 return None
256
257 content = response.content.decode("utf-8")
258 return json.loads(content)
bool delete_submodel_descriptor_by_id(self, str submodel_identifier)
Deletes a Submodel Descriptor, i.e.
dict|None get_all_submodel_descriptors(self, int limit=100, str cursor="")
Returns all Submodel Descriptors.
bool put_submodel_descriptor_by_id(self, str submodel_identifier, dict request_body)
Creates or updates an existing Submodel Descriptor.
dict|None get_submodel_descriptor_by_id(self, str submodel_identifier)
Returns the Submodel Descriptor for the given submodel identifier.
dict|None post_submodel_descriptor(self, dict request_body)
Creates a new Submodel Descriptor, i.e.
dict|None get_self_description(self)
Returns the self-describing information of a network resource (ServiceDescription).
__init__(self, "AasHttpClient" client)
Initializes the SubmodelRegistryImplementation with the given client.