azure-mgmt-agricultureplatform 1.0.0b1__py3-none-any.whl

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 (28) hide show
  1. azure/mgmt/agricultureplatform/__init__.py +32 -0
  2. azure/mgmt/agricultureplatform/_client.py +137 -0
  3. azure/mgmt/agricultureplatform/_configuration.py +80 -0
  4. azure/mgmt/agricultureplatform/_patch.py +21 -0
  5. azure/mgmt/agricultureplatform/_utils/__init__.py +6 -0
  6. azure/mgmt/agricultureplatform/_utils/model_base.py +1337 -0
  7. azure/mgmt/agricultureplatform/_utils/serialization.py +2041 -0
  8. azure/mgmt/agricultureplatform/_version.py +9 -0
  9. azure/mgmt/agricultureplatform/aio/__init__.py +29 -0
  10. azure/mgmt/agricultureplatform/aio/_client.py +141 -0
  11. azure/mgmt/agricultureplatform/aio/_configuration.py +80 -0
  12. azure/mgmt/agricultureplatform/aio/_patch.py +21 -0
  13. azure/mgmt/agricultureplatform/aio/operations/__init__.py +27 -0
  14. azure/mgmt/agricultureplatform/aio/operations/_operations.py +1102 -0
  15. azure/mgmt/agricultureplatform/aio/operations/_patch.py +21 -0
  16. azure/mgmt/agricultureplatform/models/__init__.py +92 -0
  17. azure/mgmt/agricultureplatform/models/_enums.py +103 -0
  18. azure/mgmt/agricultureplatform/models/_models.py +1037 -0
  19. azure/mgmt/agricultureplatform/models/_patch.py +21 -0
  20. azure/mgmt/agricultureplatform/operations/__init__.py +27 -0
  21. azure/mgmt/agricultureplatform/operations/_operations.py +1303 -0
  22. azure/mgmt/agricultureplatform/operations/_patch.py +21 -0
  23. azure/mgmt/agricultureplatform/py.typed +1 -0
  24. azure_mgmt_agricultureplatform-1.0.0b1.dist-info/METADATA +94 -0
  25. azure_mgmt_agricultureplatform-1.0.0b1.dist-info/RECORD +28 -0
  26. azure_mgmt_agricultureplatform-1.0.0b1.dist-info/WHEEL +5 -0
  27. azure_mgmt_agricultureplatform-1.0.0b1.dist-info/licenses/LICENSE +21 -0
  28. azure_mgmt_agricultureplatform-1.0.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2041 @@
1
+ # pylint: disable=line-too-long,useless-suppression,too-many-lines
2
+ # coding=utf-8
3
+ # --------------------------------------------------------------------------
4
+ # Copyright (c) Microsoft Corporation. All rights reserved.
5
+ # Licensed under the MIT License. See License.txt in the project root for license information.
6
+ # Code generated by Microsoft (R) Python Code Generator.
7
+ # Changes may cause incorrect behavior and will be lost if the code is regenerated.
8
+ # --------------------------------------------------------------------------
9
+
10
+ # pyright: reportUnnecessaryTypeIgnoreComment=false
11
+
12
+ from base64 import b64decode, b64encode
13
+ import calendar
14
+ import datetime
15
+ import decimal
16
+ import email
17
+ from enum import Enum
18
+ import json
19
+ import logging
20
+ import re
21
+ import sys
22
+ import codecs
23
+ from typing import (
24
+ Any,
25
+ cast,
26
+ Optional,
27
+ Union,
28
+ AnyStr,
29
+ IO,
30
+ Mapping,
31
+ Callable,
32
+ MutableMapping,
33
+ )
34
+
35
+ try:
36
+ from urllib import quote # type: ignore
37
+ except ImportError:
38
+ from urllib.parse import quote
39
+ import xml.etree.ElementTree as ET
40
+
41
+ import isodate # type: ignore
42
+ from typing_extensions import Self
43
+
44
+ from azure.core.exceptions import DeserializationError, SerializationError
45
+ from azure.core.serialization import NULL as CoreNull
46
+
47
+ _BOM = codecs.BOM_UTF8.decode(encoding="utf-8")
48
+
49
+ JSON = MutableMapping[str, Any]
50
+
51
+
52
+ class RawDeserializer:
53
+
54
+ # Accept "text" because we're open minded people...
55
+ JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$")
56
+
57
+ # Name used in context
58
+ CONTEXT_NAME = "deserialized_data"
59
+
60
+ @classmethod
61
+ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any:
62
+ """Decode data according to content-type.
63
+
64
+ Accept a stream of data as well, but will be load at once in memory for now.
65
+
66
+ If no content-type, will return the string version (not bytes, not stream)
67
+
68
+ :param data: Input, could be bytes or stream (will be decoded with UTF8) or text
69
+ :type data: str or bytes or IO
70
+ :param str content_type: The content type.
71
+ :return: The deserialized data.
72
+ :rtype: object
73
+ """
74
+ if hasattr(data, "read"):
75
+ # Assume a stream
76
+ data = cast(IO, data).read()
77
+
78
+ if isinstance(data, bytes):
79
+ data_as_str = data.decode(encoding="utf-8-sig")
80
+ else:
81
+ # Explain to mypy the correct type.
82
+ data_as_str = cast(str, data)
83
+
84
+ # Remove Byte Order Mark if present in string
85
+ data_as_str = data_as_str.lstrip(_BOM)
86
+
87
+ if content_type is None:
88
+ return data
89
+
90
+ if cls.JSON_REGEXP.match(content_type):
91
+ try:
92
+ return json.loads(data_as_str)
93
+ except ValueError as err:
94
+ raise DeserializationError("JSON is invalid: {}".format(err), err) from err
95
+ elif "xml" in (content_type or []):
96
+ try:
97
+
98
+ try:
99
+ if isinstance(data, unicode): # type: ignore
100
+ # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string
101
+ data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore
102
+ except NameError:
103
+ pass
104
+
105
+ return ET.fromstring(data_as_str) # nosec
106
+ except ET.ParseError as err:
107
+ # It might be because the server has an issue, and returned JSON with
108
+ # content-type XML....
109
+ # So let's try a JSON load, and if it's still broken
110
+ # let's flow the initial exception
111
+ def _json_attemp(data):
112
+ try:
113
+ return True, json.loads(data)
114
+ except ValueError:
115
+ return False, None # Don't care about this one
116
+
117
+ success, json_result = _json_attemp(data)
118
+ if success:
119
+ return json_result
120
+ # If i'm here, it's not JSON, it's not XML, let's scream
121
+ # and raise the last context in this block (the XML exception)
122
+ # The function hack is because Py2.7 messes up with exception
123
+ # context otherwise.
124
+ _LOGGER.critical("Wasn't XML not JSON, failing")
125
+ raise DeserializationError("XML is invalid") from err
126
+ elif content_type.startswith("text/"):
127
+ return data_as_str
128
+ raise DeserializationError("Cannot deserialize content-type: {}".format(content_type))
129
+
130
+ @classmethod
131
+ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any:
132
+ """Deserialize from HTTP response.
133
+
134
+ Use bytes and headers to NOT use any requests/aiohttp or whatever
135
+ specific implementation.
136
+ Headers will tested for "content-type"
137
+
138
+ :param bytes body_bytes: The body of the response.
139
+ :param dict headers: The headers of the response.
140
+ :returns: The deserialized data.
141
+ :rtype: object
142
+ """
143
+ # Try to use content-type from headers if available
144
+ content_type = None
145
+ if "content-type" in headers:
146
+ content_type = headers["content-type"].split(";")[0].strip().lower()
147
+ # Ouch, this server did not declare what it sent...
148
+ # Let's guess it's JSON...
149
+ # Also, since Autorest was considering that an empty body was a valid JSON,
150
+ # need that test as well....
151
+ else:
152
+ content_type = "application/json"
153
+
154
+ if body_bytes:
155
+ return cls.deserialize_from_text(body_bytes, content_type)
156
+ return None
157
+
158
+
159
+ _LOGGER = logging.getLogger(__name__)
160
+
161
+ try:
162
+ _long_type = long # type: ignore
163
+ except NameError:
164
+ _long_type = int
165
+
166
+ TZ_UTC = datetime.timezone.utc
167
+
168
+ _FLATTEN = re.compile(r"(?<!\\)\.")
169
+
170
+
171
+ def attribute_transformer(key, attr_desc, value): # pylint: disable=unused-argument
172
+ """A key transformer that returns the Python attribute.
173
+
174
+ :param str key: The attribute name
175
+ :param dict attr_desc: The attribute metadata
176
+ :param object value: The value
177
+ :returns: A key using attribute name
178
+ :rtype: str
179
+ """
180
+ return (key, value)
181
+
182
+
183
+ def full_restapi_key_transformer(key, attr_desc, value): # pylint: disable=unused-argument
184
+ """A key transformer that returns the full RestAPI key path.
185
+
186
+ :param str key: The attribute name
187
+ :param dict attr_desc: The attribute metadata
188
+ :param object value: The value
189
+ :returns: A list of keys using RestAPI syntax.
190
+ :rtype: list
191
+ """
192
+ keys = _FLATTEN.split(attr_desc["key"])
193
+ return ([_decode_attribute_map_key(k) for k in keys], value)
194
+
195
+
196
+ def last_restapi_key_transformer(key, attr_desc, value):
197
+ """A key transformer that returns the last RestAPI key.
198
+
199
+ :param str key: The attribute name
200
+ :param dict attr_desc: The attribute metadata
201
+ :param object value: The value
202
+ :returns: The last RestAPI key.
203
+ :rtype: str
204
+ """
205
+ key, value = full_restapi_key_transformer(key, attr_desc, value)
206
+ return (key[-1], value)
207
+
208
+
209
+ def _create_xml_node(tag, prefix=None, ns=None):
210
+ """Create a XML node.
211
+
212
+ :param str tag: The tag name
213
+ :param str prefix: The prefix
214
+ :param str ns: The namespace
215
+ :return: The XML node
216
+ :rtype: xml.etree.ElementTree.Element
217
+ """
218
+ if prefix and ns:
219
+ ET.register_namespace(prefix, ns)
220
+ if ns:
221
+ return ET.Element("{" + ns + "}" + tag)
222
+ return ET.Element(tag)
223
+
224
+
225
+ class Model:
226
+ """Mixin for all client request body/response body models to support
227
+ serialization and deserialization.
228
+ """
229
+
230
+ _subtype_map: dict[str, dict[str, Any]] = {}
231
+ _attribute_map: dict[str, dict[str, Any]] = {}
232
+ _validation: dict[str, dict[str, Any]] = {}
233
+
234
+ def __init__(self, **kwargs: Any) -> None:
235
+ self.additional_properties: Optional[dict[str, Any]] = {}
236
+ for k in kwargs: # pylint: disable=consider-using-dict-items
237
+ if k not in self._attribute_map:
238
+ _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__)
239
+ elif k in self._validation and self._validation[k].get("readonly", False):
240
+ _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__)
241
+ else:
242
+ setattr(self, k, kwargs[k])
243
+
244
+ def __eq__(self, other: Any) -> bool:
245
+ """Compare objects by comparing all attributes.
246
+
247
+ :param object other: The object to compare
248
+ :returns: True if objects are equal
249
+ :rtype: bool
250
+ """
251
+ if isinstance(other, self.__class__):
252
+ return self.__dict__ == other.__dict__
253
+ return False
254
+
255
+ def __ne__(self, other: Any) -> bool:
256
+ """Compare objects by comparing all attributes.
257
+
258
+ :param object other: The object to compare
259
+ :returns: True if objects are not equal
260
+ :rtype: bool
261
+ """
262
+ return not self.__eq__(other)
263
+
264
+ def __str__(self) -> str:
265
+ return str(self.__dict__)
266
+
267
+ @classmethod
268
+ def enable_additional_properties_sending(cls) -> None:
269
+ cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"}
270
+
271
+ @classmethod
272
+ def is_xml_model(cls) -> bool:
273
+ try:
274
+ cls._xml_map # type: ignore
275
+ except AttributeError:
276
+ return False
277
+ return True
278
+
279
+ @classmethod
280
+ def _create_xml_node(cls):
281
+ """Create XML node.
282
+
283
+ :returns: The XML node
284
+ :rtype: xml.etree.ElementTree.Element
285
+ """
286
+ try:
287
+ xml_map = cls._xml_map # type: ignore
288
+ except AttributeError:
289
+ xml_map = {}
290
+
291
+ return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None))
292
+
293
+ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON:
294
+ """Return the JSON that would be sent to server from this model.
295
+
296
+ This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.
297
+
298
+ If you want XML serialization, you can pass the kwargs is_xml=True.
299
+
300
+ :param bool keep_readonly: If you want to serialize the readonly attributes
301
+ :returns: A dict JSON compatible object
302
+ :rtype: dict
303
+ """
304
+ serializer = Serializer(self._infer_class_models())
305
+ return serializer._serialize( # type: ignore # pylint: disable=protected-access
306
+ self, keep_readonly=keep_readonly, **kwargs
307
+ )
308
+
309
+ def as_dict(
310
+ self,
311
+ keep_readonly: bool = True,
312
+ key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer,
313
+ **kwargs: Any
314
+ ) -> JSON:
315
+ """Return a dict that can be serialized using json.dump.
316
+
317
+ Advanced usage might optionally use a callback as parameter:
318
+
319
+ .. code::python
320
+
321
+ def my_key_transformer(key, attr_desc, value):
322
+ return key
323
+
324
+ Key is the attribute name used in Python. Attr_desc
325
+ is a dict of metadata. Currently contains 'type' with the
326
+ msrest type and 'key' with the RestAPI encoded key.
327
+ Value is the current value in this object.
328
+
329
+ The string returned will be used to serialize the key.
330
+ If the return type is a list, this is considered hierarchical
331
+ result dict.
332
+
333
+ See the three examples in this file:
334
+
335
+ - attribute_transformer
336
+ - full_restapi_key_transformer
337
+ - last_restapi_key_transformer
338
+
339
+ If you want XML serialization, you can pass the kwargs is_xml=True.
340
+
341
+ :param bool keep_readonly: If you want to serialize the readonly attributes
342
+ :param function key_transformer: A key transformer function.
343
+ :returns: A dict JSON compatible object
344
+ :rtype: dict
345
+ """
346
+ serializer = Serializer(self._infer_class_models())
347
+ return serializer._serialize( # type: ignore # pylint: disable=protected-access
348
+ self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs
349
+ )
350
+
351
+ @classmethod
352
+ def _infer_class_models(cls):
353
+ try:
354
+ str_models = cls.__module__.rsplit(".", 1)[0]
355
+ models = sys.modules[str_models]
356
+ client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
357
+ if cls.__name__ not in client_models:
358
+ raise ValueError("Not Autorest generated code")
359
+ except Exception: # pylint: disable=broad-exception-caught
360
+ # Assume it's not Autorest generated (tests?). Add ourselves as dependencies.
361
+ client_models = {cls.__name__: cls}
362
+ return client_models
363
+
364
+ @classmethod
365
+ def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self:
366
+ """Parse a str using the RestAPI syntax and return a model.
367
+
368
+ :param str data: A str using RestAPI structure. JSON by default.
369
+ :param str content_type: JSON by default, set application/xml if XML.
370
+ :returns: An instance of this model
371
+ :raises DeserializationError: if something went wrong
372
+ :rtype: Self
373
+ """
374
+ deserializer = Deserializer(cls._infer_class_models())
375
+ return deserializer(cls.__name__, data, content_type=content_type) # type: ignore
376
+
377
+ @classmethod
378
+ def from_dict(
379
+ cls,
380
+ data: Any,
381
+ key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None,
382
+ content_type: Optional[str] = None,
383
+ ) -> Self:
384
+ """Parse a dict using given key extractor return a model.
385
+
386
+ By default consider key
387
+ extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor
388
+ and last_rest_key_case_insensitive_extractor)
389
+
390
+ :param dict data: A dict using RestAPI structure
391
+ :param function key_extractors: A key extractor function.
392
+ :param str content_type: JSON by default, set application/xml if XML.
393
+ :returns: An instance of this model
394
+ :raises DeserializationError: if something went wrong
395
+ :rtype: Self
396
+ """
397
+ deserializer = Deserializer(cls._infer_class_models())
398
+ deserializer.key_extractors = ( # type: ignore
399
+ [ # type: ignore
400
+ attribute_key_case_insensitive_extractor,
401
+ rest_key_case_insensitive_extractor,
402
+ last_rest_key_case_insensitive_extractor,
403
+ ]
404
+ if key_extractors is None
405
+ else key_extractors
406
+ )
407
+ return deserializer(cls.__name__, data, content_type=content_type) # type: ignore
408
+
409
+ @classmethod
410
+ def _flatten_subtype(cls, key, objects):
411
+ if "_subtype_map" not in cls.__dict__:
412
+ return {}
413
+ result = dict(cls._subtype_map[key])
414
+ for valuetype in cls._subtype_map[key].values():
415
+ result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access
416
+ return result
417
+
418
+ @classmethod
419
+ def _classify(cls, response, objects):
420
+ """Check the class _subtype_map for any child classes.
421
+ We want to ignore any inherited _subtype_maps.
422
+
423
+ :param dict response: The initial data
424
+ :param dict objects: The class objects
425
+ :returns: The class to be used
426
+ :rtype: class
427
+ """
428
+ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys():
429
+ subtype_value = None
430
+
431
+ if not isinstance(response, ET.Element):
432
+ rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1]
433
+ subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None)
434
+ else:
435
+ subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response)
436
+ if subtype_value:
437
+ # Try to match base class. Can be class name only
438
+ # (bug to fix in Autorest to support x-ms-discriminator-name)
439
+ if cls.__name__ == subtype_value:
440
+ return cls
441
+ flatten_mapping_type = cls._flatten_subtype(subtype_key, objects)
442
+ try:
443
+ return objects[flatten_mapping_type[subtype_value]] # type: ignore
444
+ except KeyError:
445
+ _LOGGER.warning(
446
+ "Subtype value %s has no mapping, use base class %s.",
447
+ subtype_value,
448
+ cls.__name__,
449
+ )
450
+ break
451
+ else:
452
+ _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__)
453
+ break
454
+ return cls
455
+
456
+ @classmethod
457
+ def _get_rest_key_parts(cls, attr_key):
458
+ """Get the RestAPI key of this attr, split it and decode part
459
+ :param str attr_key: Attribute key must be in attribute_map.
460
+ :returns: A list of RestAPI part
461
+ :rtype: list
462
+ """
463
+ rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"])
464
+ return [_decode_attribute_map_key(key_part) for key_part in rest_split_key]
465
+
466
+
467
+ def _decode_attribute_map_key(key):
468
+ """This decode a key in an _attribute_map to the actual key we want to look at
469
+ inside the received data.
470
+
471
+ :param str key: A key string from the generated code
472
+ :returns: The decoded key
473
+ :rtype: str
474
+ """
475
+ return key.replace("\\.", ".")
476
+
477
+
478
+ class Serializer: # pylint: disable=too-many-public-methods
479
+ """Request object model serializer."""
480
+
481
+ basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
482
+
483
+ _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()}
484
+ days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"}
485
+ months = {
486
+ 1: "Jan",
487
+ 2: "Feb",
488
+ 3: "Mar",
489
+ 4: "Apr",
490
+ 5: "May",
491
+ 6: "Jun",
492
+ 7: "Jul",
493
+ 8: "Aug",
494
+ 9: "Sep",
495
+ 10: "Oct",
496
+ 11: "Nov",
497
+ 12: "Dec",
498
+ }
499
+ validation = {
500
+ "min_length": lambda x, y: len(x) < y,
501
+ "max_length": lambda x, y: len(x) > y,
502
+ "minimum": lambda x, y: x < y,
503
+ "maximum": lambda x, y: x > y,
504
+ "minimum_ex": lambda x, y: x <= y,
505
+ "maximum_ex": lambda x, y: x >= y,
506
+ "min_items": lambda x, y: len(x) < y,
507
+ "max_items": lambda x, y: len(x) > y,
508
+ "pattern": lambda x, y: not re.match(y, x, re.UNICODE),
509
+ "unique": lambda x, y: len(x) != len(set(x)),
510
+ "multiple": lambda x, y: x % y != 0,
511
+ }
512
+
513
+ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None:
514
+ self.serialize_type = {
515
+ "iso-8601": Serializer.serialize_iso,
516
+ "rfc-1123": Serializer.serialize_rfc,
517
+ "unix-time": Serializer.serialize_unix,
518
+ "duration": Serializer.serialize_duration,
519
+ "date": Serializer.serialize_date,
520
+ "time": Serializer.serialize_time,
521
+ "decimal": Serializer.serialize_decimal,
522
+ "long": Serializer.serialize_long,
523
+ "bytearray": Serializer.serialize_bytearray,
524
+ "base64": Serializer.serialize_base64,
525
+ "object": self.serialize_object,
526
+ "[]": self.serialize_iter,
527
+ "{}": self.serialize_dict,
528
+ }
529
+ self.dependencies: dict[str, type] = dict(classes) if classes else {}
530
+ self.key_transformer = full_restapi_key_transformer
531
+ self.client_side_validation = True
532
+
533
+ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals
534
+ self, target_obj, data_type=None, **kwargs
535
+ ):
536
+ """Serialize data into a string according to type.
537
+
538
+ :param object target_obj: The data to be serialized.
539
+ :param str data_type: The type to be serialized from.
540
+ :rtype: str, dict
541
+ :raises SerializationError: if serialization fails.
542
+ :returns: The serialized data.
543
+ """
544
+ key_transformer = kwargs.get("key_transformer", self.key_transformer)
545
+ keep_readonly = kwargs.get("keep_readonly", False)
546
+ if target_obj is None:
547
+ return None
548
+
549
+ attr_name = None
550
+ class_name = target_obj.__class__.__name__
551
+
552
+ if data_type:
553
+ return self.serialize_data(target_obj, data_type, **kwargs)
554
+
555
+ if not hasattr(target_obj, "_attribute_map"):
556
+ data_type = type(target_obj).__name__
557
+ if data_type in self.basic_types.values():
558
+ return self.serialize_data(target_obj, data_type, **kwargs)
559
+
560
+ # Force "is_xml" kwargs if we detect a XML model
561
+ try:
562
+ is_xml_model_serialization = kwargs["is_xml"]
563
+ except KeyError:
564
+ is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model())
565
+
566
+ serialized = {}
567
+ if is_xml_model_serialization:
568
+ serialized = target_obj._create_xml_node() # pylint: disable=protected-access
569
+ try:
570
+ attributes = target_obj._attribute_map # pylint: disable=protected-access
571
+ for attr, attr_desc in attributes.items():
572
+ attr_name = attr
573
+ if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access
574
+ attr_name, {}
575
+ ).get("readonly", False):
576
+ continue
577
+
578
+ if attr_name == "additional_properties" and attr_desc["key"] == "":
579
+ if target_obj.additional_properties is not None:
580
+ serialized |= target_obj.additional_properties
581
+ continue
582
+ try:
583
+
584
+ orig_attr = getattr(target_obj, attr)
585
+ if is_xml_model_serialization:
586
+ pass # Don't provide "transformer" for XML for now. Keep "orig_attr"
587
+ else: # JSON
588
+ keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr)
589
+ keys = keys if isinstance(keys, list) else [keys]
590
+
591
+ kwargs["serialization_ctxt"] = attr_desc
592
+ new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs)
593
+
594
+ if is_xml_model_serialization:
595
+ xml_desc = attr_desc.get("xml", {})
596
+ xml_name = xml_desc.get("name", attr_desc["key"])
597
+ xml_prefix = xml_desc.get("prefix", None)
598
+ xml_ns = xml_desc.get("ns", None)
599
+ if xml_desc.get("attr", False):
600
+ if xml_ns:
601
+ ET.register_namespace(xml_prefix, xml_ns)
602
+ xml_name = "{{{}}}{}".format(xml_ns, xml_name)
603
+ serialized.set(xml_name, new_attr) # type: ignore
604
+ continue
605
+ if xml_desc.get("text", False):
606
+ serialized.text = new_attr # type: ignore
607
+ continue
608
+ if isinstance(new_attr, list):
609
+ serialized.extend(new_attr) # type: ignore
610
+ elif isinstance(new_attr, ET.Element):
611
+ # If the down XML has no XML/Name,
612
+ # we MUST replace the tag with the local tag. But keeping the namespaces.
613
+ if "name" not in getattr(orig_attr, "_xml_map", {}):
614
+ splitted_tag = new_attr.tag.split("}")
615
+ if len(splitted_tag) == 2: # Namespace
616
+ new_attr.tag = "}".join([splitted_tag[0], xml_name])
617
+ else:
618
+ new_attr.tag = xml_name
619
+ serialized.append(new_attr) # type: ignore
620
+ else: # That's a basic type
621
+ # Integrate namespace if necessary
622
+ local_node = _create_xml_node(xml_name, xml_prefix, xml_ns)
623
+ local_node.text = str(new_attr)
624
+ serialized.append(local_node) # type: ignore
625
+ else: # JSON
626
+ for k in reversed(keys): # type: ignore
627
+ new_attr = {k: new_attr}
628
+
629
+ _new_attr = new_attr
630
+ _serialized = serialized
631
+ for k in keys: # type: ignore
632
+ if k not in _serialized:
633
+ _serialized.update(_new_attr) # type: ignore
634
+ _new_attr = _new_attr[k] # type: ignore
635
+ _serialized = _serialized[k]
636
+ except ValueError as err:
637
+ if isinstance(err, SerializationError):
638
+ raise
639
+
640
+ except (AttributeError, KeyError, TypeError) as err:
641
+ msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj))
642
+ raise SerializationError(msg) from err
643
+ return serialized
644
+
645
+ def body(self, data, data_type, **kwargs):
646
+ """Serialize data intended for a request body.
647
+
648
+ :param object data: The data to be serialized.
649
+ :param str data_type: The type to be serialized from.
650
+ :rtype: dict
651
+ :raises SerializationError: if serialization fails.
652
+ :raises ValueError: if data is None
653
+ :returns: The serialized request body
654
+ """
655
+
656
+ # Just in case this is a dict
657
+ internal_data_type_str = data_type.strip("[]{}")
658
+ internal_data_type = self.dependencies.get(internal_data_type_str, None)
659
+ try:
660
+ is_xml_model_serialization = kwargs["is_xml"]
661
+ except KeyError:
662
+ if internal_data_type and issubclass(internal_data_type, Model):
663
+ is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model())
664
+ else:
665
+ is_xml_model_serialization = False
666
+ if internal_data_type and not isinstance(internal_data_type, Enum):
667
+ try:
668
+ deserializer = Deserializer(self.dependencies)
669
+ # Since it's on serialization, it's almost sure that format is not JSON REST
670
+ # We're not able to deal with additional properties for now.
671
+ deserializer.additional_properties_detection = False
672
+ if is_xml_model_serialization:
673
+ deserializer.key_extractors = [ # type: ignore
674
+ attribute_key_case_insensitive_extractor,
675
+ ]
676
+ else:
677
+ deserializer.key_extractors = [
678
+ rest_key_case_insensitive_extractor,
679
+ attribute_key_case_insensitive_extractor,
680
+ last_rest_key_case_insensitive_extractor,
681
+ ]
682
+ data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access
683
+ except DeserializationError as err:
684
+ raise SerializationError("Unable to build a model: " + str(err)) from err
685
+
686
+ return self._serialize(data, data_type, **kwargs)
687
+
688
+ def url(self, name, data, data_type, **kwargs):
689
+ """Serialize data intended for a URL path.
690
+
691
+ :param str name: The name of the URL path parameter.
692
+ :param object data: The data to be serialized.
693
+ :param str data_type: The type to be serialized from.
694
+ :rtype: str
695
+ :returns: The serialized URL path
696
+ :raises TypeError: if serialization fails.
697
+ :raises ValueError: if data is None
698
+ """
699
+ try:
700
+ output = self.serialize_data(data, data_type, **kwargs)
701
+ if data_type == "bool":
702
+ output = json.dumps(output)
703
+
704
+ if kwargs.get("skip_quote") is True:
705
+ output = str(output)
706
+ output = output.replace("{", quote("{")).replace("}", quote("}"))
707
+ else:
708
+ output = quote(str(output), safe="")
709
+ except SerializationError as exc:
710
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
711
+ return output
712
+
713
+ def query(self, name, data, data_type, **kwargs):
714
+ """Serialize data intended for a URL query.
715
+
716
+ :param str name: The name of the query parameter.
717
+ :param object data: The data to be serialized.
718
+ :param str data_type: The type to be serialized from.
719
+ :rtype: str, list
720
+ :raises TypeError: if serialization fails.
721
+ :raises ValueError: if data is None
722
+ :returns: The serialized query parameter
723
+ """
724
+ try:
725
+ # Treat the list aside, since we don't want to encode the div separator
726
+ if data_type.startswith("["):
727
+ internal_data_type = data_type[1:-1]
728
+ do_quote = not kwargs.get("skip_quote", False)
729
+ return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs)
730
+
731
+ # Not a list, regular serialization
732
+ output = self.serialize_data(data, data_type, **kwargs)
733
+ if data_type == "bool":
734
+ output = json.dumps(output)
735
+ if kwargs.get("skip_quote") is True:
736
+ output = str(output)
737
+ else:
738
+ output = quote(str(output), safe="")
739
+ except SerializationError as exc:
740
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
741
+ return str(output)
742
+
743
+ def header(self, name, data, data_type, **kwargs):
744
+ """Serialize data intended for a request header.
745
+
746
+ :param str name: The name of the header.
747
+ :param object data: The data to be serialized.
748
+ :param str data_type: The type to be serialized from.
749
+ :rtype: str
750
+ :raises TypeError: if serialization fails.
751
+ :raises ValueError: if data is None
752
+ :returns: The serialized header
753
+ """
754
+ try:
755
+ if data_type in ["[str]"]:
756
+ data = ["" if d is None else d for d in data]
757
+
758
+ output = self.serialize_data(data, data_type, **kwargs)
759
+ if data_type == "bool":
760
+ output = json.dumps(output)
761
+ except SerializationError as exc:
762
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
763
+ return str(output)
764
+
765
+ def serialize_data(self, data, data_type, **kwargs):
766
+ """Serialize generic data according to supplied data type.
767
+
768
+ :param object data: The data to be serialized.
769
+ :param str data_type: The type to be serialized from.
770
+ :raises AttributeError: if required data is None.
771
+ :raises ValueError: if data is None
772
+ :raises SerializationError: if serialization fails.
773
+ :returns: The serialized data.
774
+ :rtype: str, int, float, bool, dict, list
775
+ """
776
+ if data is None:
777
+ raise ValueError("No value for given attribute")
778
+
779
+ try:
780
+ if data is CoreNull:
781
+ return None
782
+ if data_type in self.basic_types.values():
783
+ return self.serialize_basic(data, data_type, **kwargs)
784
+
785
+ if data_type in self.serialize_type:
786
+ return self.serialize_type[data_type](data, **kwargs)
787
+
788
+ # If dependencies is empty, try with current data class
789
+ # It has to be a subclass of Enum anyway
790
+ enum_type = self.dependencies.get(data_type, cast(type, data.__class__))
791
+ if issubclass(enum_type, Enum):
792
+ return Serializer.serialize_enum(data, enum_obj=enum_type)
793
+
794
+ iter_type = data_type[0] + data_type[-1]
795
+ if iter_type in self.serialize_type:
796
+ return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs)
797
+
798
+ except (ValueError, TypeError) as err:
799
+ msg = "Unable to serialize value: {!r} as type: {!r}."
800
+ raise SerializationError(msg.format(data, data_type)) from err
801
+ return self._serialize(data, **kwargs)
802
+
803
+ @classmethod
804
+ def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements
805
+ custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type)
806
+ if custom_serializer:
807
+ return custom_serializer
808
+ if kwargs.get("is_xml", False):
809
+ return cls._xml_basic_types_serializers.get(data_type)
810
+
811
+ @classmethod
812
+ def serialize_basic(cls, data, data_type, **kwargs):
813
+ """Serialize basic builting data type.
814
+ Serializes objects to str, int, float or bool.
815
+
816
+ Possible kwargs:
817
+ - basic_types_serializers dict[str, callable] : If set, use the callable as serializer
818
+ - is_xml bool : If set, use xml_basic_types_serializers
819
+
820
+ :param obj data: Object to be serialized.
821
+ :param str data_type: Type of object in the iterable.
822
+ :rtype: str, int, float, bool
823
+ :return: serialized object
824
+ :raises TypeError: raise if data_type is not one of str, int, float, bool.
825
+ """
826
+ custom_serializer = cls._get_custom_serializers(data_type, **kwargs)
827
+ if custom_serializer:
828
+ return custom_serializer(data)
829
+ if data_type == "str":
830
+ return cls.serialize_unicode(data)
831
+ if data_type == "int":
832
+ return int(data)
833
+ if data_type == "float":
834
+ return float(data)
835
+ if data_type == "bool":
836
+ return bool(data)
837
+ raise TypeError("Unknown basic data type: {}".format(data_type))
838
+
839
+ @classmethod
840
+ def serialize_unicode(cls, data):
841
+ """Special handling for serializing unicode strings in Py2.
842
+ Encode to UTF-8 if unicode, otherwise handle as a str.
843
+
844
+ :param str data: Object to be serialized.
845
+ :rtype: str
846
+ :return: serialized object
847
+ """
848
+ try: # If I received an enum, return its value
849
+ return data.value
850
+ except AttributeError:
851
+ pass
852
+
853
+ try:
854
+ if isinstance(data, unicode): # type: ignore
855
+ # Don't change it, JSON and XML ElementTree are totally able
856
+ # to serialize correctly u'' strings
857
+ return data
858
+ except NameError:
859
+ return str(data)
860
+ return str(data)
861
+
862
+ def serialize_iter(self, data, iter_type, div=None, **kwargs):
863
+ """Serialize iterable.
864
+
865
+ Supported kwargs:
866
+ - serialization_ctxt dict : The current entry of _attribute_map, or same format.
867
+ serialization_ctxt['type'] should be same as data_type.
868
+ - is_xml bool : If set, serialize as XML
869
+
870
+ :param list data: Object to be serialized.
871
+ :param str iter_type: Type of object in the iterable.
872
+ :param str div: If set, this str will be used to combine the elements
873
+ in the iterable into a combined string. Default is 'None'.
874
+ Defaults to False.
875
+ :rtype: list, str
876
+ :return: serialized iterable
877
+ """
878
+ if isinstance(data, str):
879
+ raise SerializationError("Refuse str type as a valid iter type.")
880
+
881
+ serialization_ctxt = kwargs.get("serialization_ctxt", {})
882
+ is_xml = kwargs.get("is_xml", False)
883
+
884
+ serialized = []
885
+ for d in data:
886
+ try:
887
+ serialized.append(self.serialize_data(d, iter_type, **kwargs))
888
+ except ValueError as err:
889
+ if isinstance(err, SerializationError):
890
+ raise
891
+ serialized.append(None)
892
+
893
+ if kwargs.get("do_quote", False):
894
+ serialized = ["" if s is None else quote(str(s), safe="") for s in serialized]
895
+
896
+ if div:
897
+ serialized = ["" if s is None else str(s) for s in serialized]
898
+ serialized = div.join(serialized)
899
+
900
+ if "xml" in serialization_ctxt or is_xml:
901
+ # XML serialization is more complicated
902
+ xml_desc = serialization_ctxt.get("xml", {})
903
+ xml_name = xml_desc.get("name")
904
+ if not xml_name:
905
+ xml_name = serialization_ctxt["key"]
906
+
907
+ # Create a wrap node if necessary (use the fact that Element and list have "append")
908
+ is_wrapped = xml_desc.get("wrapped", False)
909
+ node_name = xml_desc.get("itemsName", xml_name)
910
+ if is_wrapped:
911
+ final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None))
912
+ else:
913
+ final_result = []
914
+ # All list elements to "local_node"
915
+ for el in serialized:
916
+ if isinstance(el, ET.Element):
917
+ el_node = el
918
+ else:
919
+ el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None))
920
+ if el is not None: # Otherwise it writes "None" :-p
921
+ el_node.text = str(el)
922
+ final_result.append(el_node)
923
+ return final_result
924
+ return serialized
925
+
926
+ def serialize_dict(self, attr, dict_type, **kwargs):
927
+ """Serialize a dictionary of objects.
928
+
929
+ :param dict attr: Object to be serialized.
930
+ :param str dict_type: Type of object in the dictionary.
931
+ :rtype: dict
932
+ :return: serialized dictionary
933
+ """
934
+ serialization_ctxt = kwargs.get("serialization_ctxt", {})
935
+ serialized = {}
936
+ for key, value in attr.items():
937
+ try:
938
+ serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs)
939
+ except ValueError as err:
940
+ if isinstance(err, SerializationError):
941
+ raise
942
+ serialized[self.serialize_unicode(key)] = None
943
+
944
+ if "xml" in serialization_ctxt:
945
+ # XML serialization is more complicated
946
+ xml_desc = serialization_ctxt["xml"]
947
+ xml_name = xml_desc["name"]
948
+
949
+ final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None))
950
+ for key, value in serialized.items():
951
+ ET.SubElement(final_result, key).text = value
952
+ return final_result
953
+
954
+ return serialized
955
+
956
+ def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements
957
+ """Serialize a generic object.
958
+ This will be handled as a dictionary. If object passed in is not
959
+ a basic type (str, int, float, dict, list) it will simply be
960
+ cast to str.
961
+
962
+ :param dict attr: Object to be serialized.
963
+ :rtype: dict or str
964
+ :return: serialized object
965
+ """
966
+ if attr is None:
967
+ return None
968
+ if isinstance(attr, ET.Element):
969
+ return attr
970
+ obj_type = type(attr)
971
+ if obj_type in self.basic_types:
972
+ return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs)
973
+ if obj_type is _long_type:
974
+ return self.serialize_long(attr)
975
+ if obj_type is str:
976
+ return self.serialize_unicode(attr)
977
+ if obj_type is datetime.datetime:
978
+ return self.serialize_iso(attr)
979
+ if obj_type is datetime.date:
980
+ return self.serialize_date(attr)
981
+ if obj_type is datetime.time:
982
+ return self.serialize_time(attr)
983
+ if obj_type is datetime.timedelta:
984
+ return self.serialize_duration(attr)
985
+ if obj_type is decimal.Decimal:
986
+ return self.serialize_decimal(attr)
987
+
988
+ # If it's a model or I know this dependency, serialize as a Model
989
+ if obj_type in self.dependencies.values() or isinstance(attr, Model):
990
+ return self._serialize(attr)
991
+
992
+ if obj_type == dict:
993
+ serialized = {}
994
+ for key, value in attr.items():
995
+ try:
996
+ serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs)
997
+ except ValueError:
998
+ serialized[self.serialize_unicode(key)] = None
999
+ return serialized
1000
+
1001
+ if obj_type == list:
1002
+ serialized = []
1003
+ for obj in attr:
1004
+ try:
1005
+ serialized.append(self.serialize_object(obj, **kwargs))
1006
+ except ValueError:
1007
+ pass
1008
+ return serialized
1009
+ return str(attr)
1010
+
1011
+ @staticmethod
1012
+ def serialize_enum(attr, enum_obj=None):
1013
+ try:
1014
+ result = attr.value
1015
+ except AttributeError:
1016
+ result = attr
1017
+ try:
1018
+ enum_obj(result) # type: ignore
1019
+ return result
1020
+ except ValueError as exc:
1021
+ for enum_value in enum_obj: # type: ignore
1022
+ if enum_value.value.lower() == str(attr).lower():
1023
+ return enum_value.value
1024
+ error = "{!r} is not valid value for enum {!r}"
1025
+ raise SerializationError(error.format(attr, enum_obj)) from exc
1026
+
1027
+ @staticmethod
1028
+ def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument
1029
+ """Serialize bytearray into base-64 string.
1030
+
1031
+ :param str attr: Object to be serialized.
1032
+ :rtype: str
1033
+ :return: serialized base64
1034
+ """
1035
+ return b64encode(attr).decode()
1036
+
1037
+ @staticmethod
1038
+ def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument
1039
+ """Serialize str into base-64 string.
1040
+
1041
+ :param str attr: Object to be serialized.
1042
+ :rtype: str
1043
+ :return: serialized base64
1044
+ """
1045
+ encoded = b64encode(attr).decode("ascii")
1046
+ return encoded.strip("=").replace("+", "-").replace("/", "_")
1047
+
1048
+ @staticmethod
1049
+ def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument
1050
+ """Serialize Decimal object to float.
1051
+
1052
+ :param decimal attr: Object to be serialized.
1053
+ :rtype: float
1054
+ :return: serialized decimal
1055
+ """
1056
+ return float(attr)
1057
+
1058
+ @staticmethod
1059
+ def serialize_long(attr, **kwargs): # pylint: disable=unused-argument
1060
+ """Serialize long (Py2) or int (Py3).
1061
+
1062
+ :param int attr: Object to be serialized.
1063
+ :rtype: int/long
1064
+ :return: serialized long
1065
+ """
1066
+ return _long_type(attr)
1067
+
1068
+ @staticmethod
1069
+ def serialize_date(attr, **kwargs): # pylint: disable=unused-argument
1070
+ """Serialize Date object into ISO-8601 formatted string.
1071
+
1072
+ :param Date attr: Object to be serialized.
1073
+ :rtype: str
1074
+ :return: serialized date
1075
+ """
1076
+ if isinstance(attr, str):
1077
+ attr = isodate.parse_date(attr)
1078
+ t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day)
1079
+ return t
1080
+
1081
+ @staticmethod
1082
+ def serialize_time(attr, **kwargs): # pylint: disable=unused-argument
1083
+ """Serialize Time object into ISO-8601 formatted string.
1084
+
1085
+ :param datetime.time attr: Object to be serialized.
1086
+ :rtype: str
1087
+ :return: serialized time
1088
+ """
1089
+ if isinstance(attr, str):
1090
+ attr = isodate.parse_time(attr)
1091
+ t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second)
1092
+ if attr.microsecond:
1093
+ t += ".{:02}".format(attr.microsecond)
1094
+ return t
1095
+
1096
+ @staticmethod
1097
+ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument
1098
+ """Serialize TimeDelta object into ISO-8601 formatted string.
1099
+
1100
+ :param TimeDelta attr: Object to be serialized.
1101
+ :rtype: str
1102
+ :return: serialized duration
1103
+ """
1104
+ if isinstance(attr, str):
1105
+ attr = isodate.parse_duration(attr)
1106
+ return isodate.duration_isoformat(attr)
1107
+
1108
+ @staticmethod
1109
+ def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument
1110
+ """Serialize Datetime object into RFC-1123 formatted string.
1111
+
1112
+ :param Datetime attr: Object to be serialized.
1113
+ :rtype: str
1114
+ :raises TypeError: if format invalid.
1115
+ :return: serialized rfc
1116
+ """
1117
+ try:
1118
+ if not attr.tzinfo:
1119
+ _LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
1120
+ utc = attr.utctimetuple()
1121
+ except AttributeError as exc:
1122
+ raise TypeError("RFC1123 object must be valid Datetime object.") from exc
1123
+
1124
+ return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format(
1125
+ Serializer.days[utc.tm_wday],
1126
+ utc.tm_mday,
1127
+ Serializer.months[utc.tm_mon],
1128
+ utc.tm_year,
1129
+ utc.tm_hour,
1130
+ utc.tm_min,
1131
+ utc.tm_sec,
1132
+ )
1133
+
1134
+ @staticmethod
1135
+ def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument
1136
+ """Serialize Datetime object into ISO-8601 formatted string.
1137
+
1138
+ :param Datetime attr: Object to be serialized.
1139
+ :rtype: str
1140
+ :raises SerializationError: if format invalid.
1141
+ :return: serialized iso
1142
+ """
1143
+ if isinstance(attr, str):
1144
+ attr = isodate.parse_datetime(attr)
1145
+ try:
1146
+ if not attr.tzinfo:
1147
+ _LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
1148
+ utc = attr.utctimetuple()
1149
+ if utc.tm_year > 9999 or utc.tm_year < 1:
1150
+ raise OverflowError("Hit max or min date")
1151
+
1152
+ microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0")
1153
+ if microseconds:
1154
+ microseconds = "." + microseconds
1155
+ date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format(
1156
+ utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec
1157
+ )
1158
+ return date + microseconds + "Z"
1159
+ except (ValueError, OverflowError) as err:
1160
+ msg = "Unable to serialize datetime object."
1161
+ raise SerializationError(msg) from err
1162
+ except AttributeError as err:
1163
+ msg = "ISO-8601 object must be valid Datetime object."
1164
+ raise TypeError(msg) from err
1165
+
1166
+ @staticmethod
1167
+ def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument
1168
+ """Serialize Datetime object into IntTime format.
1169
+ This is represented as seconds.
1170
+
1171
+ :param Datetime attr: Object to be serialized.
1172
+ :rtype: int
1173
+ :raises SerializationError: if format invalid
1174
+ :return: serialied unix
1175
+ """
1176
+ if isinstance(attr, int):
1177
+ return attr
1178
+ try:
1179
+ if not attr.tzinfo:
1180
+ _LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
1181
+ return int(calendar.timegm(attr.utctimetuple()))
1182
+ except AttributeError as exc:
1183
+ raise TypeError("Unix time object must be valid Datetime object.") from exc
1184
+
1185
+
1186
+ def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
1187
+ key = attr_desc["key"]
1188
+ working_data = data
1189
+
1190
+ while "." in key:
1191
+ # Need the cast, as for some reasons "split" is typed as list[str | Any]
1192
+ dict_keys = cast(list[str], _FLATTEN.split(key))
1193
+ if len(dict_keys) == 1:
1194
+ key = _decode_attribute_map_key(dict_keys[0])
1195
+ break
1196
+ working_key = _decode_attribute_map_key(dict_keys[0])
1197
+ working_data = working_data.get(working_key, data)
1198
+ if working_data is None:
1199
+ # If at any point while following flatten JSON path see None, it means
1200
+ # that all properties under are None as well
1201
+ return None
1202
+ key = ".".join(dict_keys[1:])
1203
+
1204
+ return working_data.get(key)
1205
+
1206
+
1207
+ def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements
1208
+ attr, attr_desc, data
1209
+ ):
1210
+ key = attr_desc["key"]
1211
+ working_data = data
1212
+
1213
+ while "." in key:
1214
+ dict_keys = _FLATTEN.split(key)
1215
+ if len(dict_keys) == 1:
1216
+ key = _decode_attribute_map_key(dict_keys[0])
1217
+ break
1218
+ working_key = _decode_attribute_map_key(dict_keys[0])
1219
+ working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data)
1220
+ if working_data is None:
1221
+ # If at any point while following flatten JSON path see None, it means
1222
+ # that all properties under are None as well
1223
+ return None
1224
+ key = ".".join(dict_keys[1:])
1225
+
1226
+ if working_data:
1227
+ return attribute_key_case_insensitive_extractor(key, None, working_data)
1228
+
1229
+
1230
+ def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
1231
+ """Extract the attribute in "data" based on the last part of the JSON path key.
1232
+
1233
+ :param str attr: The attribute to extract
1234
+ :param dict attr_desc: The attribute description
1235
+ :param dict data: The data to extract from
1236
+ :rtype: object
1237
+ :returns: The extracted attribute
1238
+ """
1239
+ key = attr_desc["key"]
1240
+ dict_keys = _FLATTEN.split(key)
1241
+ return attribute_key_extractor(dict_keys[-1], None, data)
1242
+
1243
+
1244
+ def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
1245
+ """Extract the attribute in "data" based on the last part of the JSON path key.
1246
+
1247
+ This is the case insensitive version of "last_rest_key_extractor"
1248
+ :param str attr: The attribute to extract
1249
+ :param dict attr_desc: The attribute description
1250
+ :param dict data: The data to extract from
1251
+ :rtype: object
1252
+ :returns: The extracted attribute
1253
+ """
1254
+ key = attr_desc["key"]
1255
+ dict_keys = _FLATTEN.split(key)
1256
+ return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data)
1257
+
1258
+
1259
+ def attribute_key_extractor(attr, _, data):
1260
+ return data.get(attr)
1261
+
1262
+
1263
+ def attribute_key_case_insensitive_extractor(attr, _, data):
1264
+ found_key = None
1265
+ lower_attr = attr.lower()
1266
+ for key in data:
1267
+ if lower_attr == key.lower():
1268
+ found_key = key
1269
+ break
1270
+
1271
+ return data.get(found_key)
1272
+
1273
+
1274
+ def _extract_name_from_internal_type(internal_type):
1275
+ """Given an internal type XML description, extract correct XML name with namespace.
1276
+
1277
+ :param dict internal_type: An model type
1278
+ :rtype: tuple
1279
+ :returns: A tuple XML name + namespace dict
1280
+ """
1281
+ internal_type_xml_map = getattr(internal_type, "_xml_map", {})
1282
+ xml_name = internal_type_xml_map.get("name", internal_type.__name__)
1283
+ xml_ns = internal_type_xml_map.get("ns", None)
1284
+ if xml_ns:
1285
+ xml_name = "{{{}}}{}".format(xml_ns, xml_name)
1286
+ return xml_name
1287
+
1288
+
1289
+ def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements
1290
+ if isinstance(data, dict):
1291
+ return None
1292
+
1293
+ # Test if this model is XML ready first
1294
+ if not isinstance(data, ET.Element):
1295
+ return None
1296
+
1297
+ xml_desc = attr_desc.get("xml", {})
1298
+ xml_name = xml_desc.get("name", attr_desc["key"])
1299
+
1300
+ # Look for a children
1301
+ is_iter_type = attr_desc["type"].startswith("[")
1302
+ is_wrapped = xml_desc.get("wrapped", False)
1303
+ internal_type = attr_desc.get("internalType", None)
1304
+ internal_type_xml_map = getattr(internal_type, "_xml_map", {})
1305
+
1306
+ # Integrate namespace if necessary
1307
+ xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None))
1308
+ if xml_ns:
1309
+ xml_name = "{{{}}}{}".format(xml_ns, xml_name)
1310
+
1311
+ # If it's an attribute, that's simple
1312
+ if xml_desc.get("attr", False):
1313
+ return data.get(xml_name)
1314
+
1315
+ # If it's x-ms-text, that's simple too
1316
+ if xml_desc.get("text", False):
1317
+ return data.text
1318
+
1319
+ # Scenario where I take the local name:
1320
+ # - Wrapped node
1321
+ # - Internal type is an enum (considered basic types)
1322
+ # - Internal type has no XML/Name node
1323
+ if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)):
1324
+ children = data.findall(xml_name)
1325
+ # If internal type has a local name and it's not a list, I use that name
1326
+ elif not is_iter_type and internal_type and "name" in internal_type_xml_map:
1327
+ xml_name = _extract_name_from_internal_type(internal_type)
1328
+ children = data.findall(xml_name)
1329
+ # That's an array
1330
+ else:
1331
+ if internal_type: # Complex type, ignore itemsName and use the complex type name
1332
+ items_name = _extract_name_from_internal_type(internal_type)
1333
+ else:
1334
+ items_name = xml_desc.get("itemsName", xml_name)
1335
+ children = data.findall(items_name)
1336
+
1337
+ if len(children) == 0:
1338
+ if is_iter_type:
1339
+ if is_wrapped:
1340
+ return None # is_wrapped no node, we want None
1341
+ return [] # not wrapped, assume empty list
1342
+ return None # Assume it's not there, maybe an optional node.
1343
+
1344
+ # If is_iter_type and not wrapped, return all found children
1345
+ if is_iter_type:
1346
+ if not is_wrapped:
1347
+ return children
1348
+ # Iter and wrapped, should have found one node only (the wrap one)
1349
+ if len(children) != 1:
1350
+ raise DeserializationError(
1351
+ "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format(
1352
+ xml_name
1353
+ )
1354
+ )
1355
+ return list(children[0]) # Might be empty list and that's ok.
1356
+
1357
+ # Here it's not a itertype, we should have found one element only or empty
1358
+ if len(children) > 1:
1359
+ raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name))
1360
+ return children[0]
1361
+
1362
+
1363
+ class Deserializer:
1364
+ """Response object model deserializer.
1365
+
1366
+ :param dict classes: Class type dictionary for deserializing complex types.
1367
+ :ivar list key_extractors: Ordered list of extractors to be used by this deserializer.
1368
+ """
1369
+
1370
+ basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
1371
+
1372
+ valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?")
1373
+
1374
+ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None:
1375
+ self.deserialize_type = {
1376
+ "iso-8601": Deserializer.deserialize_iso,
1377
+ "rfc-1123": Deserializer.deserialize_rfc,
1378
+ "unix-time": Deserializer.deserialize_unix,
1379
+ "duration": Deserializer.deserialize_duration,
1380
+ "date": Deserializer.deserialize_date,
1381
+ "time": Deserializer.deserialize_time,
1382
+ "decimal": Deserializer.deserialize_decimal,
1383
+ "long": Deserializer.deserialize_long,
1384
+ "bytearray": Deserializer.deserialize_bytearray,
1385
+ "base64": Deserializer.deserialize_base64,
1386
+ "object": self.deserialize_object,
1387
+ "[]": self.deserialize_iter,
1388
+ "{}": self.deserialize_dict,
1389
+ }
1390
+ self.deserialize_expected_types = {
1391
+ "duration": (isodate.Duration, datetime.timedelta),
1392
+ "iso-8601": (datetime.datetime),
1393
+ }
1394
+ self.dependencies: dict[str, type] = dict(classes) if classes else {}
1395
+ self.key_extractors = [rest_key_extractor, xml_key_extractor]
1396
+ # Additional properties only works if the "rest_key_extractor" is used to
1397
+ # extract the keys. Making it to work whatever the key extractor is too much
1398
+ # complicated, with no real scenario for now.
1399
+ # So adding a flag to disable additional properties detection. This flag should be
1400
+ # used if your expect the deserialization to NOT come from a JSON REST syntax.
1401
+ # Otherwise, result are unexpected
1402
+ self.additional_properties_detection = True
1403
+
1404
+ def __call__(self, target_obj, response_data, content_type=None):
1405
+ """Call the deserializer to process a REST response.
1406
+
1407
+ :param str target_obj: Target data type to deserialize to.
1408
+ :param requests.Response response_data: REST response object.
1409
+ :param str content_type: Swagger "produces" if available.
1410
+ :raises DeserializationError: if deserialization fails.
1411
+ :return: Deserialized object.
1412
+ :rtype: object
1413
+ """
1414
+ data = self._unpack_content(response_data, content_type)
1415
+ return self._deserialize(target_obj, data)
1416
+
1417
+ def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements
1418
+ """Call the deserializer on a model.
1419
+
1420
+ Data needs to be already deserialized as JSON or XML ElementTree
1421
+
1422
+ :param str target_obj: Target data type to deserialize to.
1423
+ :param object data: Object to deserialize.
1424
+ :raises DeserializationError: if deserialization fails.
1425
+ :return: Deserialized object.
1426
+ :rtype: object
1427
+ """
1428
+ # This is already a model, go recursive just in case
1429
+ if hasattr(data, "_attribute_map"):
1430
+ constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")]
1431
+ try:
1432
+ for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access
1433
+ if attr in constants:
1434
+ continue
1435
+ value = getattr(data, attr)
1436
+ if value is None:
1437
+ continue
1438
+ local_type = mapconfig["type"]
1439
+ internal_data_type = local_type.strip("[]{}")
1440
+ if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum):
1441
+ continue
1442
+ setattr(data, attr, self._deserialize(local_type, value))
1443
+ return data
1444
+ except AttributeError:
1445
+ return
1446
+
1447
+ response, class_name = self._classify_target(target_obj, data)
1448
+
1449
+ if isinstance(response, str):
1450
+ return self.deserialize_data(data, response)
1451
+ if isinstance(response, type) and issubclass(response, Enum):
1452
+ return self.deserialize_enum(data, response)
1453
+
1454
+ if data is None or data is CoreNull:
1455
+ return data
1456
+ try:
1457
+ attributes = response._attribute_map # type: ignore # pylint: disable=protected-access
1458
+ d_attrs = {}
1459
+ for attr, attr_desc in attributes.items():
1460
+ # Check empty string. If it's not empty, someone has a real "additionalProperties"...
1461
+ if attr == "additional_properties" and attr_desc["key"] == "":
1462
+ continue
1463
+ raw_value = None
1464
+ # Enhance attr_desc with some dynamic data
1465
+ attr_desc = attr_desc.copy() # Do a copy, do not change the real one
1466
+ internal_data_type = attr_desc["type"].strip("[]{}")
1467
+ if internal_data_type in self.dependencies:
1468
+ attr_desc["internalType"] = self.dependencies[internal_data_type]
1469
+
1470
+ for key_extractor in self.key_extractors:
1471
+ found_value = key_extractor(attr, attr_desc, data)
1472
+ if found_value is not None:
1473
+ if raw_value is not None and raw_value != found_value:
1474
+ msg = (
1475
+ "Ignoring extracted value '%s' from %s for key '%s'"
1476
+ " (duplicate extraction, follow extractors order)"
1477
+ )
1478
+ _LOGGER.warning(msg, found_value, key_extractor, attr)
1479
+ continue
1480
+ raw_value = found_value
1481
+
1482
+ value = self.deserialize_data(raw_value, attr_desc["type"])
1483
+ d_attrs[attr] = value
1484
+ except (AttributeError, TypeError, KeyError) as err:
1485
+ msg = "Unable to deserialize to object: " + class_name # type: ignore
1486
+ raise DeserializationError(msg) from err
1487
+ additional_properties = self._build_additional_properties(attributes, data)
1488
+ return self._instantiate_model(response, d_attrs, additional_properties)
1489
+
1490
+ def _build_additional_properties(self, attribute_map, data):
1491
+ if not self.additional_properties_detection:
1492
+ return None
1493
+ if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "":
1494
+ # Check empty string. If it's not empty, someone has a real "additionalProperties"
1495
+ return None
1496
+ if isinstance(data, ET.Element):
1497
+ data = {el.tag: el.text for el in data}
1498
+
1499
+ known_keys = {
1500
+ _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0])
1501
+ for desc in attribute_map.values()
1502
+ if desc["key"] != ""
1503
+ }
1504
+ present_keys = set(data.keys())
1505
+ missing_keys = present_keys - known_keys
1506
+ return {key: data[key] for key in missing_keys}
1507
+
1508
+ def _classify_target(self, target, data):
1509
+ """Check to see whether the deserialization target object can
1510
+ be classified into a subclass.
1511
+ Once classification has been determined, initialize object.
1512
+
1513
+ :param str target: The target object type to deserialize to.
1514
+ :param str/dict data: The response data to deserialize.
1515
+ :return: The classified target object and its class name.
1516
+ :rtype: tuple
1517
+ """
1518
+ if target is None:
1519
+ return None, None
1520
+
1521
+ if isinstance(target, str):
1522
+ try:
1523
+ target = self.dependencies[target]
1524
+ except KeyError:
1525
+ return target, target
1526
+
1527
+ try:
1528
+ target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access
1529
+ except AttributeError:
1530
+ pass # Target is not a Model, no classify
1531
+ return target, target.__class__.__name__ # type: ignore
1532
+
1533
+ def failsafe_deserialize(self, target_obj, data, content_type=None):
1534
+ """Ignores any errors encountered in deserialization,
1535
+ and falls back to not deserializing the object. Recommended
1536
+ for use in error deserialization, as we want to return the
1537
+ HttpResponseError to users, and not have them deal with
1538
+ a deserialization error.
1539
+
1540
+ :param str target_obj: The target object type to deserialize to.
1541
+ :param str/dict data: The response data to deserialize.
1542
+ :param str content_type: Swagger "produces" if available.
1543
+ :return: Deserialized object.
1544
+ :rtype: object
1545
+ """
1546
+ try:
1547
+ return self(target_obj, data, content_type=content_type)
1548
+ except: # pylint: disable=bare-except
1549
+ _LOGGER.debug(
1550
+ "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True
1551
+ )
1552
+ return None
1553
+
1554
+ @staticmethod
1555
+ def _unpack_content(raw_data, content_type=None):
1556
+ """Extract the correct structure for deserialization.
1557
+
1558
+ If raw_data is a PipelineResponse, try to extract the result of RawDeserializer.
1559
+ if we can't, raise. Your Pipeline should have a RawDeserializer.
1560
+
1561
+ If not a pipeline response and raw_data is bytes or string, use content-type
1562
+ to decode it. If no content-type, try JSON.
1563
+
1564
+ If raw_data is something else, bypass all logic and return it directly.
1565
+
1566
+ :param obj raw_data: Data to be processed.
1567
+ :param str content_type: How to parse if raw_data is a string/bytes.
1568
+ :raises JSONDecodeError: If JSON is requested and parsing is impossible.
1569
+ :raises UnicodeDecodeError: If bytes is not UTF8
1570
+ :rtype: object
1571
+ :return: Unpacked content.
1572
+ """
1573
+ # Assume this is enough to detect a Pipeline Response without importing it
1574
+ context = getattr(raw_data, "context", {})
1575
+ if context:
1576
+ if RawDeserializer.CONTEXT_NAME in context:
1577
+ return context[RawDeserializer.CONTEXT_NAME]
1578
+ raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize")
1579
+
1580
+ # Assume this is enough to recognize universal_http.ClientResponse without importing it
1581
+ if hasattr(raw_data, "body"):
1582
+ return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers)
1583
+
1584
+ # Assume this enough to recognize requests.Response without importing it.
1585
+ if hasattr(raw_data, "_content_consumed"):
1586
+ return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers)
1587
+
1588
+ if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"):
1589
+ return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore
1590
+ return raw_data
1591
+
1592
+ def _instantiate_model(self, response, attrs, additional_properties=None):
1593
+ """Instantiate a response model passing in deserialized args.
1594
+
1595
+ :param Response response: The response model class.
1596
+ :param dict attrs: The deserialized response attributes.
1597
+ :param dict additional_properties: Additional properties to be set.
1598
+ :rtype: Response
1599
+ :return: The instantiated response model.
1600
+ """
1601
+ if callable(response):
1602
+ subtype = getattr(response, "_subtype_map", {})
1603
+ try:
1604
+ readonly = [
1605
+ k
1606
+ for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore
1607
+ if v.get("readonly")
1608
+ ]
1609
+ const = [
1610
+ k
1611
+ for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore
1612
+ if v.get("constant")
1613
+ ]
1614
+ kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const}
1615
+ response_obj = response(**kwargs)
1616
+ for attr in readonly:
1617
+ setattr(response_obj, attr, attrs.get(attr))
1618
+ if additional_properties:
1619
+ response_obj.additional_properties = additional_properties # type: ignore
1620
+ return response_obj
1621
+ except TypeError as err:
1622
+ msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore
1623
+ raise DeserializationError(msg + str(err)) from err
1624
+ else:
1625
+ try:
1626
+ for attr, value in attrs.items():
1627
+ setattr(response, attr, value)
1628
+ return response
1629
+ except Exception as exp:
1630
+ msg = "Unable to populate response model. "
1631
+ msg += "Type: {}, Error: {}".format(type(response), exp)
1632
+ raise DeserializationError(msg) from exp
1633
+
1634
+ def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements
1635
+ """Process data for deserialization according to data type.
1636
+
1637
+ :param str data: The response string to be deserialized.
1638
+ :param str data_type: The type to deserialize to.
1639
+ :raises DeserializationError: if deserialization fails.
1640
+ :return: Deserialized object.
1641
+ :rtype: object
1642
+ """
1643
+ if data is None:
1644
+ return data
1645
+
1646
+ try:
1647
+ if not data_type:
1648
+ return data
1649
+ if data_type in self.basic_types.values():
1650
+ return self.deserialize_basic(data, data_type)
1651
+ if data_type in self.deserialize_type:
1652
+ if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())):
1653
+ return data
1654
+
1655
+ is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment
1656
+ "object",
1657
+ "[]",
1658
+ r"{}",
1659
+ ]
1660
+ if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text:
1661
+ return None
1662
+ data_val = self.deserialize_type[data_type](data)
1663
+ return data_val
1664
+
1665
+ iter_type = data_type[0] + data_type[-1]
1666
+ if iter_type in self.deserialize_type:
1667
+ return self.deserialize_type[iter_type](data, data_type[1:-1])
1668
+
1669
+ obj_type = self.dependencies[data_type]
1670
+ if issubclass(obj_type, Enum):
1671
+ if isinstance(data, ET.Element):
1672
+ data = data.text
1673
+ return self.deserialize_enum(data, obj_type)
1674
+
1675
+ except (ValueError, TypeError, AttributeError) as err:
1676
+ msg = "Unable to deserialize response data."
1677
+ msg += " Data: {}, {}".format(data, data_type)
1678
+ raise DeserializationError(msg) from err
1679
+ return self._deserialize(obj_type, data)
1680
+
1681
+ def deserialize_iter(self, attr, iter_type):
1682
+ """Deserialize an iterable.
1683
+
1684
+ :param list attr: Iterable to be deserialized.
1685
+ :param str iter_type: The type of object in the iterable.
1686
+ :return: Deserialized iterable.
1687
+ :rtype: list
1688
+ """
1689
+ if attr is None:
1690
+ return None
1691
+ if isinstance(attr, ET.Element): # If I receive an element here, get the children
1692
+ attr = list(attr)
1693
+ if not isinstance(attr, (list, set)):
1694
+ raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr)))
1695
+ return [self.deserialize_data(a, iter_type) for a in attr]
1696
+
1697
+ def deserialize_dict(self, attr, dict_type):
1698
+ """Deserialize a dictionary.
1699
+
1700
+ :param dict/list attr: Dictionary to be deserialized. Also accepts
1701
+ a list of key, value pairs.
1702
+ :param str dict_type: The object type of the items in the dictionary.
1703
+ :return: Deserialized dictionary.
1704
+ :rtype: dict
1705
+ """
1706
+ if isinstance(attr, list):
1707
+ return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr}
1708
+
1709
+ if isinstance(attr, ET.Element):
1710
+ # Transform <Key>value</Key> into {"Key": "value"}
1711
+ attr = {el.tag: el.text for el in attr}
1712
+ return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()}
1713
+
1714
+ def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements
1715
+ """Deserialize a generic object.
1716
+ This will be handled as a dictionary.
1717
+
1718
+ :param dict attr: Dictionary to be deserialized.
1719
+ :return: Deserialized object.
1720
+ :rtype: dict
1721
+ :raises TypeError: if non-builtin datatype encountered.
1722
+ """
1723
+ if attr is None:
1724
+ return None
1725
+ if isinstance(attr, ET.Element):
1726
+ # Do no recurse on XML, just return the tree as-is
1727
+ return attr
1728
+ if isinstance(attr, str):
1729
+ return self.deserialize_basic(attr, "str")
1730
+ obj_type = type(attr)
1731
+ if obj_type in self.basic_types:
1732
+ return self.deserialize_basic(attr, self.basic_types[obj_type])
1733
+ if obj_type is _long_type:
1734
+ return self.deserialize_long(attr)
1735
+
1736
+ if obj_type == dict:
1737
+ deserialized = {}
1738
+ for key, value in attr.items():
1739
+ try:
1740
+ deserialized[key] = self.deserialize_object(value, **kwargs)
1741
+ except ValueError:
1742
+ deserialized[key] = None
1743
+ return deserialized
1744
+
1745
+ if obj_type == list:
1746
+ deserialized = []
1747
+ for obj in attr:
1748
+ try:
1749
+ deserialized.append(self.deserialize_object(obj, **kwargs))
1750
+ except ValueError:
1751
+ pass
1752
+ return deserialized
1753
+
1754
+ error = "Cannot deserialize generic object with type: "
1755
+ raise TypeError(error + str(obj_type))
1756
+
1757
+ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements
1758
+ """Deserialize basic builtin data type from string.
1759
+ Will attempt to convert to str, int, float and bool.
1760
+ This function will also accept '1', '0', 'true' and 'false' as
1761
+ valid bool values.
1762
+
1763
+ :param str attr: response string to be deserialized.
1764
+ :param str data_type: deserialization data type.
1765
+ :return: Deserialized basic type.
1766
+ :rtype: str, int, float or bool
1767
+ :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool.
1768
+ """
1769
+ # If we're here, data is supposed to be a basic type.
1770
+ # If it's still an XML node, take the text
1771
+ if isinstance(attr, ET.Element):
1772
+ attr = attr.text
1773
+ if not attr:
1774
+ if data_type == "str":
1775
+ # None or '', node <a/> is empty string.
1776
+ return ""
1777
+ # None or '', node <a/> with a strong type is None.
1778
+ # Don't try to model "empty bool" or "empty int"
1779
+ return None
1780
+
1781
+ if data_type == "bool":
1782
+ if attr in [True, False, 1, 0]:
1783
+ return bool(attr)
1784
+ if isinstance(attr, str):
1785
+ if attr.lower() in ["true", "1"]:
1786
+ return True
1787
+ if attr.lower() in ["false", "0"]:
1788
+ return False
1789
+ raise TypeError("Invalid boolean value: {}".format(attr))
1790
+
1791
+ if data_type == "str":
1792
+ return self.deserialize_unicode(attr)
1793
+ if data_type == "int":
1794
+ return int(attr)
1795
+ if data_type == "float":
1796
+ return float(attr)
1797
+ raise TypeError("Unknown basic data type: {}".format(data_type))
1798
+
1799
+ @staticmethod
1800
+ def deserialize_unicode(data):
1801
+ """Preserve unicode objects in Python 2, otherwise return data
1802
+ as a string.
1803
+
1804
+ :param str data: response string to be deserialized.
1805
+ :return: Deserialized string.
1806
+ :rtype: str or unicode
1807
+ """
1808
+ # We might be here because we have an enum modeled as string,
1809
+ # and we try to deserialize a partial dict with enum inside
1810
+ if isinstance(data, Enum):
1811
+ return data
1812
+
1813
+ # Consider this is real string
1814
+ try:
1815
+ if isinstance(data, unicode): # type: ignore
1816
+ return data
1817
+ except NameError:
1818
+ return str(data)
1819
+ return str(data)
1820
+
1821
+ @staticmethod
1822
+ def deserialize_enum(data, enum_obj):
1823
+ """Deserialize string into enum object.
1824
+
1825
+ If the string is not a valid enum value it will be returned as-is
1826
+ and a warning will be logged.
1827
+
1828
+ :param str data: Response string to be deserialized. If this value is
1829
+ None or invalid it will be returned as-is.
1830
+ :param Enum enum_obj: Enum object to deserialize to.
1831
+ :return: Deserialized enum object.
1832
+ :rtype: Enum
1833
+ """
1834
+ if isinstance(data, enum_obj) or data is None:
1835
+ return data
1836
+ if isinstance(data, Enum):
1837
+ data = data.value
1838
+ if isinstance(data, int):
1839
+ # Workaround. We might consider remove it in the future.
1840
+ try:
1841
+ return list(enum_obj.__members__.values())[data]
1842
+ except IndexError as exc:
1843
+ error = "{!r} is not a valid index for enum {!r}"
1844
+ raise DeserializationError(error.format(data, enum_obj)) from exc
1845
+ try:
1846
+ return enum_obj(str(data))
1847
+ except ValueError:
1848
+ for enum_value in enum_obj:
1849
+ if enum_value.value.lower() == str(data).lower():
1850
+ return enum_value
1851
+ # We don't fail anymore for unknown value, we deserialize as a string
1852
+ _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj)
1853
+ return Deserializer.deserialize_unicode(data)
1854
+
1855
+ @staticmethod
1856
+ def deserialize_bytearray(attr):
1857
+ """Deserialize string into bytearray.
1858
+
1859
+ :param str attr: response string to be deserialized.
1860
+ :return: Deserialized bytearray
1861
+ :rtype: bytearray
1862
+ :raises TypeError: if string format invalid.
1863
+ """
1864
+ if isinstance(attr, ET.Element):
1865
+ attr = attr.text
1866
+ return bytearray(b64decode(attr)) # type: ignore
1867
+
1868
+ @staticmethod
1869
+ def deserialize_base64(attr):
1870
+ """Deserialize base64 encoded string into string.
1871
+
1872
+ :param str attr: response string to be deserialized.
1873
+ :return: Deserialized base64 string
1874
+ :rtype: bytearray
1875
+ :raises TypeError: if string format invalid.
1876
+ """
1877
+ if isinstance(attr, ET.Element):
1878
+ attr = attr.text
1879
+ padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore
1880
+ attr = attr + padding # type: ignore
1881
+ encoded = attr.replace("-", "+").replace("_", "/")
1882
+ return b64decode(encoded)
1883
+
1884
+ @staticmethod
1885
+ def deserialize_decimal(attr):
1886
+ """Deserialize string into Decimal object.
1887
+
1888
+ :param str attr: response string to be deserialized.
1889
+ :return: Deserialized decimal
1890
+ :raises DeserializationError: if string format invalid.
1891
+ :rtype: decimal
1892
+ """
1893
+ if isinstance(attr, ET.Element):
1894
+ attr = attr.text
1895
+ try:
1896
+ return decimal.Decimal(str(attr)) # type: ignore
1897
+ except decimal.DecimalException as err:
1898
+ msg = "Invalid decimal {}".format(attr)
1899
+ raise DeserializationError(msg) from err
1900
+
1901
+ @staticmethod
1902
+ def deserialize_long(attr):
1903
+ """Deserialize string into long (Py2) or int (Py3).
1904
+
1905
+ :param str attr: response string to be deserialized.
1906
+ :return: Deserialized int
1907
+ :rtype: long or int
1908
+ :raises ValueError: if string format invalid.
1909
+ """
1910
+ if isinstance(attr, ET.Element):
1911
+ attr = attr.text
1912
+ return _long_type(attr) # type: ignore
1913
+
1914
+ @staticmethod
1915
+ def deserialize_duration(attr):
1916
+ """Deserialize ISO-8601 formatted string into TimeDelta object.
1917
+
1918
+ :param str attr: response string to be deserialized.
1919
+ :return: Deserialized duration
1920
+ :rtype: TimeDelta
1921
+ :raises DeserializationError: if string format invalid.
1922
+ """
1923
+ if isinstance(attr, ET.Element):
1924
+ attr = attr.text
1925
+ try:
1926
+ duration = isodate.parse_duration(attr)
1927
+ except (ValueError, OverflowError, AttributeError) as err:
1928
+ msg = "Cannot deserialize duration object."
1929
+ raise DeserializationError(msg) from err
1930
+ return duration
1931
+
1932
+ @staticmethod
1933
+ def deserialize_date(attr):
1934
+ """Deserialize ISO-8601 formatted string into Date object.
1935
+
1936
+ :param str attr: response string to be deserialized.
1937
+ :return: Deserialized date
1938
+ :rtype: Date
1939
+ :raises DeserializationError: if string format invalid.
1940
+ """
1941
+ if isinstance(attr, ET.Element):
1942
+ attr = attr.text
1943
+ if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore
1944
+ raise DeserializationError("Date must have only digits and -. Received: %s" % attr)
1945
+ # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception.
1946
+ return isodate.parse_date(attr, defaultmonth=0, defaultday=0)
1947
+
1948
+ @staticmethod
1949
+ def deserialize_time(attr):
1950
+ """Deserialize ISO-8601 formatted string into time object.
1951
+
1952
+ :param str attr: response string to be deserialized.
1953
+ :return: Deserialized time
1954
+ :rtype: datetime.time
1955
+ :raises DeserializationError: if string format invalid.
1956
+ """
1957
+ if isinstance(attr, ET.Element):
1958
+ attr = attr.text
1959
+ if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore
1960
+ raise DeserializationError("Date must have only digits and -. Received: %s" % attr)
1961
+ return isodate.parse_time(attr)
1962
+
1963
+ @staticmethod
1964
+ def deserialize_rfc(attr):
1965
+ """Deserialize RFC-1123 formatted string into Datetime object.
1966
+
1967
+ :param str attr: response string to be deserialized.
1968
+ :return: Deserialized RFC datetime
1969
+ :rtype: Datetime
1970
+ :raises DeserializationError: if string format invalid.
1971
+ """
1972
+ if isinstance(attr, ET.Element):
1973
+ attr = attr.text
1974
+ try:
1975
+ parsed_date = email.utils.parsedate_tz(attr) # type: ignore
1976
+ date_obj = datetime.datetime(
1977
+ *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60))
1978
+ )
1979
+ if not date_obj.tzinfo:
1980
+ date_obj = date_obj.astimezone(tz=TZ_UTC)
1981
+ except ValueError as err:
1982
+ msg = "Cannot deserialize to rfc datetime object."
1983
+ raise DeserializationError(msg) from err
1984
+ return date_obj
1985
+
1986
+ @staticmethod
1987
+ def deserialize_iso(attr):
1988
+ """Deserialize ISO-8601 formatted string into Datetime object.
1989
+
1990
+ :param str attr: response string to be deserialized.
1991
+ :return: Deserialized ISO datetime
1992
+ :rtype: Datetime
1993
+ :raises DeserializationError: if string format invalid.
1994
+ """
1995
+ if isinstance(attr, ET.Element):
1996
+ attr = attr.text
1997
+ try:
1998
+ attr = attr.upper() # type: ignore
1999
+ match = Deserializer.valid_date.match(attr)
2000
+ if not match:
2001
+ raise ValueError("Invalid datetime string: " + attr)
2002
+
2003
+ check_decimal = attr.split(".")
2004
+ if len(check_decimal) > 1:
2005
+ decimal_str = ""
2006
+ for digit in check_decimal[1]:
2007
+ if digit.isdigit():
2008
+ decimal_str += digit
2009
+ else:
2010
+ break
2011
+ if len(decimal_str) > 6:
2012
+ attr = attr.replace(decimal_str, decimal_str[0:6])
2013
+
2014
+ date_obj = isodate.parse_datetime(attr)
2015
+ test_utc = date_obj.utctimetuple()
2016
+ if test_utc.tm_year > 9999 or test_utc.tm_year < 1:
2017
+ raise OverflowError("Hit max or min date")
2018
+ except (ValueError, OverflowError, AttributeError) as err:
2019
+ msg = "Cannot deserialize datetime object."
2020
+ raise DeserializationError(msg) from err
2021
+ return date_obj
2022
+
2023
+ @staticmethod
2024
+ def deserialize_unix(attr):
2025
+ """Serialize Datetime object into IntTime format.
2026
+ This is represented as seconds.
2027
+
2028
+ :param int attr: Object to be serialized.
2029
+ :return: Deserialized datetime
2030
+ :rtype: Datetime
2031
+ :raises DeserializationError: if format invalid
2032
+ """
2033
+ if isinstance(attr, ET.Element):
2034
+ attr = int(attr.text) # type: ignore
2035
+ try:
2036
+ attr = int(attr)
2037
+ date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC)
2038
+ except ValueError as err:
2039
+ msg = "Cannot deserialize to unix datetime object."
2040
+ raise DeserializationError(msg) from err
2041
+ return date_obj