openmeter 1.0.0b53__py3-none-any.whl → 2.0.0__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.

Potentially problematic release.


This version of openmeter might be problematic. Click here for more details.

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