-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathserialization.py
1994 lines (1728 loc) · 77 KB
/
serialization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
from base64 import b64decode, b64encode
import calendar
import datetime
import decimal
import email
from enum import Enum
import json
import logging
import re
import sys
try:
from urllib import quote # type: ignore
except ImportError:
from urllib.parse import quote # type: ignore
import xml.etree.ElementTree as ET
import isodate
from typing import Dict, Any
from .exceptions import (
ValidationError,
SerializationError,
DeserializationError,
raise_with_traceback)
try:
basestring # type: ignore
unicode_str = unicode # type: ignore
except NameError:
basestring = str # type: ignore
unicode_str = str # type: ignore
_LOGGER = logging.getLogger(__name__)
try:
_long_type = long # type: ignore
except NameError:
_long_type = int
class UTC(datetime.tzinfo):
"""Time Zone info for handling UTC"""
def utcoffset(self, dt):
"""UTF offset for UTC is 0."""
return datetime.timedelta(0)
def tzname(self, dt):
"""Timestamp representation."""
return "Z"
def dst(self, dt):
"""No daylight saving for UTC."""
return datetime.timedelta(hours=1)
try:
from datetime import timezone as _FixedOffset
except ImportError: # Python 2.7
class _FixedOffset(datetime.tzinfo): # type: ignore
"""Fixed offset in minutes east from UTC.
Copy/pasted from Python doc
:param datetime.timedelta offset: offset in timedelta format
"""
def __init__(self, offset):
self.__offset = offset
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return str(self.__offset.total_seconds()/3600)
def __repr__(self):
return "<FixedOffset {}>".format(self.tzname(None))
def dst(self, dt):
return datetime.timedelta(0)
def __getinitargs__(self):
return (self.__offset,)
try:
from datetime import timezone
TZ_UTC = timezone.utc # type: ignore
except ImportError:
TZ_UTC = UTC() # type: ignore
_FLATTEN = re.compile(r"(?<!\\)\.")
def attribute_transformer(key, attr_desc, value):
"""A key transformer that returns the Python attribute.
:param str key: The attribute name
:param dict attr_desc: The attribute metadata
:param object value: The value
:returns: A key using attribute name
"""
return (key, value)
def full_restapi_key_transformer(key, attr_desc, value):
"""A key transformer that returns the full RestAPI key path.
:param str _: The attribute name
:param dict attr_desc: The attribute metadata
:param object value: The value
:returns: A list of keys using RestAPI syntax.
"""
keys = _FLATTEN.split(attr_desc['key'])
return ([_decode_attribute_map_key(k) for k in keys], value)
def last_restapi_key_transformer(key, attr_desc, value):
"""A key transformer that returns the last RestAPI key.
:param str key: The attribute name
:param dict attr_desc: The attribute metadata
:param object value: The value
:returns: The last RestAPI key.
"""
key, value = full_restapi_key_transformer(key, attr_desc, value)
return (key[-1], value)
def _recursive_validate(attr_name, attr_type, data):
result = []
if attr_type.startswith('[') and data is not None:
for content in data:
result += _recursive_validate(attr_name+" content", attr_type[1:-1], content)
elif attr_type.startswith('{') and data is not None:
if not hasattr(data, 'values'):
raise ValidationError("type", attr_name, attr_type)
for content in data.values():
result += _recursive_validate(attr_name+" content", attr_type[1:-1], content)
elif hasattr(data, '_validation'):
return data.validate()
return result
def _create_xml_node(tag, prefix=None, ns=None):
"""Create a XML node."""
if prefix and ns:
ET.register_namespace(prefix, ns)
if ns:
return ET.Element("{"+ns+"}"+tag)
else:
return ET.Element(tag)
class Model(object):
"""Mixin for all client request body/response body models to support
serialization and deserialization.
"""
_subtype_map = {} # type: Dict[str, Dict[str, Any]]
_attribute_map = {} # type: Dict[str, Dict[str, Any]]
_validation = {} # type: Dict[str, Dict[str, Any]]
def __init__(self, **kwargs):
self.additional_properties = {}
for k in kwargs:
if k not in self._attribute_map:
_LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__)
elif k in self._validation and self._validation[k].get("readonly", False):
_LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__)
else:
setattr(self, k, kwargs[k])
def __eq__(self, other):
"""Compare objects by comparing all attributes."""
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
return False
def __ne__(self, other):
"""Compare objects by comparing all attributes."""
return not self.__eq__(other)
def __str__(self):
return str(self.__dict__)
@classmethod
def enable_additional_properties_sending(cls):
cls._attribute_map['additional_properties'] = {'key': '', 'type': '{object}'}
@classmethod
def is_xml_model(cls):
try:
cls._xml_map
except AttributeError:
return False
return True
@classmethod
def _create_xml_node(cls):
"""Create XML node.
"""
try:
xml_map = cls._xml_map
except AttributeError:
xml_map = {}
return _create_xml_node(
xml_map.get('name', cls.__name__),
xml_map.get("prefix", None),
xml_map.get("ns", None)
)
def validate(self):
"""Validate this model recursively and return a list of ValidationError.
:returns: A list of validation error
:rtype: list
"""
validation_result = []
for attr_name, value in [(attr, getattr(self, attr)) for attr in self._attribute_map]:
attr_desc = self._attribute_map[attr_name]
if attr_name == "additional_properties" and attr_desc["key"] == '':
# Do NOT validate additional_properties
continue
attr_type = attr_desc['type']
try:
debug_name = "{}.{}".format(self.__class__.__name__, attr_name)
# https://github.com/Azure/msrest-for-python/issues/85
if value is not None and attr_type in Serializer.basic_types.values():
value = Serializer.serialize_basic(value, attr_type)
Serializer.validate(value, debug_name, **self._validation.get(attr_name, {}))
except ValidationError as validation_error:
validation_result.append(validation_error)
validation_result += _recursive_validate(attr_name, attr_type, value)
return validation_result
def serialize(self, keep_readonly=False, **kwargs):
"""Return the JSON that would be sent to azure from this model.
This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.
If you want XML serialization, you can pass the kwargs is_xml=True.
:param bool keep_readonly: If you want to serialize the readonly attributes
:returns: A dict JSON compatible object
:rtype: dict
"""
serializer = Serializer(self._infer_class_models())
return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs)
def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs):
"""Return a dict that can be JSONify using json.dump.
Advanced usage might optionally use a callback as parameter:
.. code::python
def my_key_transformer(key, attr_desc, value):
return key
Key is the attribute name used in Python. Attr_desc
is a dict of metadata. Currently contains 'type' with the
msrest type and 'key' with the RestAPI encoded key.
Value is the current value in this object.
The string returned will be used to serialize the key.
If the return type is a list, this is considered hierarchical
result dict.
See the three examples in this file:
- attribute_transformer
- full_restapi_key_transformer
- last_restapi_key_transformer
If you want XML serialization, you can pass the kwargs is_xml=True.
:param function key_transformer: A key transformer function.
:returns: A dict JSON compatible object
:rtype: dict
"""
serializer = Serializer(self._infer_class_models())
return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs)
@classmethod
def _infer_class_models(cls):
try:
str_models = cls.__module__.rsplit('.', 1)[0]
models = sys.modules[str_models]
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
if cls.__name__ not in client_models:
raise ValueError("Not Autorest generated code")
except Exception:
# Assume it's not Autorest generated (tests?). Add ourselves as dependencies.
client_models = {cls.__name__: cls}
return client_models
@classmethod
def deserialize(cls, data, content_type=None):
"""Parse a str using the RestAPI syntax and return a model.
:param str data: A str using RestAPI structure. JSON by default.
:param str content_type: JSON by default, set application/xml if XML.
:returns: An instance of this model
:raises: DeserializationError if something went wrong
"""
deserializer = Deserializer(cls._infer_class_models())
return deserializer(cls.__name__, data, content_type=content_type)
@classmethod
def from_dict(cls, data, key_extractors=None, content_type=None):
"""Parse a dict using given key extractor return a model.
By default consider key
extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor
and last_rest_key_case_insensitive_extractor)
:param dict data: A dict using RestAPI structure
:param str content_type: JSON by default, set application/xml if XML.
:returns: An instance of this model
:raises: DeserializationError if something went wrong
"""
deserializer = Deserializer(cls._infer_class_models())
deserializer.key_extractors = [
attribute_key_case_insensitive_extractor,
rest_key_case_insensitive_extractor,
last_rest_key_case_insensitive_extractor
] if key_extractors is None else key_extractors
return deserializer(cls.__name__, data, content_type=content_type)
@classmethod
def _flatten_subtype(cls, key, objects):
if '_subtype_map' not in cls.__dict__:
return {}
result = dict(cls._subtype_map[key])
for valuetype in cls._subtype_map[key].values():
result.update(objects[valuetype]._flatten_subtype(key, objects))
return result
@classmethod
def _classify(cls, response, objects):
"""Check the class _subtype_map for any child classes.
We want to ignore any inherited _subtype_maps.
Remove the polymorphic key from the initial data.
"""
for subtype_key in cls.__dict__.get('_subtype_map', {}).keys():
subtype_value = None
if not isinstance(response, ET.Element):
rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1]
subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None)
else:
subtype_value = xml_key_extractor(
subtype_key,
cls._attribute_map[subtype_key],
response
)
if subtype_value:
# Try to match base class. Can be class name only
# (bug to fix in Autorest to support x-ms-discriminator-name)
if cls.__name__ == subtype_value:
return cls
flatten_mapping_type = cls._flatten_subtype(subtype_key, objects)
try:
return objects[flatten_mapping_type[subtype_value]]
except KeyError:
_LOGGER.warning(
"Subtype value %s has no mapping, use base class %s.",
subtype_value,
cls.__name__,
)
break
else:
_LOGGER.warning(
"Discriminator %s is absent or null, use base class %s.",
subtype_key,
cls.__name__
)
break
return cls
@classmethod
def _get_rest_key_parts(cls, attr_key):
"""Get the RestAPI key of this attr, split it and decode part
:param str attr_key: Attribute key must be in attribute_map.
:returns: A list of RestAPI part
:rtype: list
"""
rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]['key'])
return [_decode_attribute_map_key(key_part) for key_part in rest_split_key]
def _decode_attribute_map_key(key):
"""This decode a key in an _attribute_map to the actual key we want to look at
inside the received data.
:param str key: A key string from the generated code
"""
return key.replace('\\.', '.')
class Serializer(object):
"""Request object model serializer."""
basic_types = {str: 'str', int: 'int', bool: 'bool', float: 'float'}
_xml_basic_types_serializers = {'bool': lambda x:str(x).lower()}
days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu",
4: "Fri", 5: "Sat", 6: "Sun"}
months = {1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun",
7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"}
validation = {
"min_length": lambda x, y: len(x) < y,
"max_length": lambda x, y: len(x) > y,
"minimum": lambda x, y: x < y,
"maximum": lambda x, y: x > y,
"minimum_ex": lambda x, y: x <= y,
"maximum_ex": lambda x, y: x >= y,
"min_items": lambda x, y: len(x) < y,
"max_items": lambda x, y: len(x) > y,
"pattern": lambda x, y: not re.match(y, x, re.UNICODE),
"unique": lambda x, y: len(x) != len(set(x)),
"multiple": lambda x, y: x % y != 0
}
def __init__(self, classes=None):
self.serialize_type = {
'iso-8601': Serializer.serialize_iso,
'rfc-1123': Serializer.serialize_rfc,
'unix-time': Serializer.serialize_unix,
'duration': Serializer.serialize_duration,
'date': Serializer.serialize_date,
'time': Serializer.serialize_time,
'decimal': Serializer.serialize_decimal,
'long': Serializer.serialize_long,
'bytearray': Serializer.serialize_bytearray,
'base64': Serializer.serialize_base64,
'object': self.serialize_object,
'[]': self.serialize_iter,
'{}': self.serialize_dict
}
self.dependencies = dict(classes) if classes else {}
self.key_transformer = full_restapi_key_transformer
self.client_side_validation = True
def _serialize(self, target_obj, data_type=None, **kwargs):
"""Serialize data into a string according to type.
:param target_obj: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str, dict
:raises: SerializationError if serialization fails.
"""
key_transformer = kwargs.get("key_transformer", self.key_transformer)
keep_readonly = kwargs.get("keep_readonly", False)
if target_obj is None:
return None
attr_name = None
class_name = target_obj.__class__.__name__
if data_type:
return self.serialize_data(
target_obj, data_type, **kwargs)
if not hasattr(target_obj, "_attribute_map"):
data_type = type(target_obj).__name__
if data_type in self.basic_types.values():
return self.serialize_data(
target_obj, data_type, **kwargs)
# Force "is_xml" kwargs if we detect a XML model
try:
is_xml_model_serialization = kwargs["is_xml"]
except KeyError:
is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model())
serialized = {}
if is_xml_model_serialization:
serialized = target_obj._create_xml_node()
try:
attributes = target_obj._attribute_map
for attr, attr_desc in attributes.items():
attr_name = attr
if not keep_readonly and target_obj._validation.get(attr_name, {}).get('readonly', False):
continue
if attr_name == "additional_properties" and attr_desc["key"] == '':
if target_obj.additional_properties is not None:
serialized.update(target_obj.additional_properties)
continue
try:
### Extract sub-data to serialize from model ###
orig_attr = getattr(target_obj, attr)
if is_xml_model_serialization:
pass # Don't provide "transformer" for XML for now. Keep "orig_attr"
else: # JSON
keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr)
keys = keys if isinstance(keys, list) else [keys]
### Serialize this data ###
kwargs["serialization_ctxt"] = attr_desc
new_attr = self.serialize_data(orig_attr, attr_desc['type'], **kwargs)
### Incorporate this data in the right place ###
if is_xml_model_serialization:
xml_desc = attr_desc.get('xml', {})
xml_name = xml_desc.get('name', attr_desc['key'])
xml_prefix = xml_desc.get('prefix', None)
xml_ns = xml_desc.get('ns', None)
if xml_desc.get("attr", False):
if xml_ns:
ET.register_namespace(xml_prefix, xml_ns)
xml_name = "{{{}}}{}".format(xml_ns, xml_name)
serialized.set(xml_name, new_attr)
continue
if xml_desc.get("text", False):
serialized.text = new_attr
continue
if isinstance(new_attr, list):
serialized.extend(new_attr)
elif isinstance(new_attr, ET.Element):
# If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces.
if 'name' not in getattr(orig_attr, '_xml_map', {}):
splitted_tag = new_attr.tag.split("}")
if len(splitted_tag) == 2: # Namespace
new_attr.tag = "}".join([splitted_tag[0], xml_name])
else:
new_attr.tag = xml_name
serialized.append(new_attr)
else: # That's a basic type
# Integrate namespace if necessary
local_node = _create_xml_node(
xml_name,
xml_prefix,
xml_ns
)
local_node.text = unicode_str(new_attr)
serialized.append(local_node)
else: # JSON
for k in reversed(keys):
unflattened = {k: new_attr}
new_attr = unflattened
_new_attr = new_attr
_serialized = serialized
for k in keys:
if k not in _serialized:
_serialized.update(_new_attr)
_new_attr = _new_attr[k]
_serialized = _serialized[k]
except ValueError as err:
if isinstance(err, SerializationError):
raise err
continue
except (AttributeError, KeyError, TypeError) as err:
msg = "Attribute {} in object {} cannot be serialized.\n{}".format(
attr_name, class_name, str(target_obj))
raise_with_traceback(SerializationError, msg, err)
else:
return serialized
def body(self, data, data_type, **kwargs):
"""Serialize data intended for a request body.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: dict
:raises: SerializationError if serialization fails.
:raises: ValueError if data is None
"""
if data is None:
raise ValidationError("required", "body", True)
# Just in case this is a dict
internal_data_type = data_type.strip('[]{}')
internal_data_type = self.dependencies.get(internal_data_type, None)
try:
is_xml_model_serialization = kwargs["is_xml"]
except KeyError:
if internal_data_type and issubclass(internal_data_type, Model):
is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model())
else:
is_xml_model_serialization = False
if internal_data_type and not isinstance(internal_data_type, Enum):
try:
deserializer = Deserializer(self.dependencies)
# Since it's on serialization, it's almost sure that format is not JSON REST
# We're not able to deal with additional properties for now.
deserializer.additional_properties_detection = False
if is_xml_model_serialization:
deserializer.key_extractors = [
attribute_key_case_insensitive_extractor,
]
else:
deserializer.key_extractors = [
rest_key_case_insensitive_extractor,
attribute_key_case_insensitive_extractor,
last_rest_key_case_insensitive_extractor
]
data = deserializer._deserialize(data_type, data)
except DeserializationError as err:
raise_with_traceback(
SerializationError, "Unable to build a model: "+str(err), err)
if self.client_side_validation:
errors = _recursive_validate(data_type, data_type, data)
if errors:
raise errors[0]
return self._serialize(data, data_type, **kwargs)
def _http_component_validation(self, data, data_type, name, **kwargs):
if self.client_side_validation:
# https://github.com/Azure/msrest-for-python/issues/85
if data is not None and data_type in self.basic_types.values():
data = self.serialize_basic(data, data_type, **kwargs)
data = self.validate(data, name, required=True, **kwargs)
return data
def url(self, name, data, data_type, **kwargs):
"""Serialize data intended for a URL path.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
"""
data = self._http_component_validation(data, data_type, name, **kwargs)
try:
output = self.serialize_data(data, data_type, **kwargs)
if data_type == 'bool':
output = json.dumps(output)
if kwargs.get('skip_quote') is True:
output = str(output)
else:
output = quote(str(output), safe='')
except SerializationError:
raise TypeError("{} must be type {}.".format(name, data_type))
else:
return output
def query(self, name, data, data_type, **kwargs):
"""Serialize data intended for a URL query.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
"""
data = self._http_component_validation(data, data_type, name, **kwargs)
try:
# Treat the list aside, since we don't want to encode the div separator
if data_type.startswith("["):
internal_data_type = data_type[1:-1]
data = [
self.serialize_data(d, internal_data_type, **kwargs) if d is not None else ""
for d
in data
]
if not kwargs.get('skip_quote', False):
data = [
quote(str(d), safe='')
for d
in data
]
return str(self.serialize_iter(data, internal_data_type, **kwargs))
# Not a list, regular serialization
output = self.serialize_data(data, data_type, **kwargs)
if data_type == 'bool':
output = json.dumps(output)
if kwargs.get('skip_quote') is True:
output = str(output)
else:
output = quote(str(output), safe='')
except SerializationError:
raise TypeError("{} must be type {}.".format(name, data_type))
else:
return str(output)
def header(self, name, data, data_type, **kwargs):
"""Serialize data intended for a request header.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
"""
data = self._http_component_validation(data, data_type, name, **kwargs)
try:
if data_type in ['[str]']:
data = ["" if d is None else d for d in data]
output = self.serialize_data(data, data_type, **kwargs)
if data_type == 'bool':
output = json.dumps(output)
except SerializationError:
raise TypeError("{} must be type {}.".format(name, data_type))
else:
return str(output)
@classmethod
def validate(cls, data, name, **kwargs):
"""Validate that a piece of data meets certain conditions"""
required = kwargs.get('required', False)
if required and data is None:
raise ValidationError("required", name, True)
elif data is None:
return
elif kwargs.get('readonly'):
return
try:
for key, value in kwargs.items():
validator = cls.validation.get(key, lambda x, y: False)
if validator(data, value):
raise ValidationError(key, name, value)
except TypeError:
raise ValidationError("unknown", name, "unknown")
else:
return data
def serialize_data(self, data, data_type, **kwargs):
"""Serialize generic data according to supplied data type.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:param bool required: Whether it's essential that the data not be
empty or None
:raises: AttributeError if required data is None.
:raises: ValueError if data is None
:raises: SerializationError if serialization fails.
"""
if data is None:
raise ValueError("No value for given attribute")
try:
if data_type in self.basic_types.values():
return self.serialize_basic(data, data_type, **kwargs)
elif data_type in self.serialize_type:
return self.serialize_type[data_type](data, **kwargs)
# If dependencies is empty, try with current data class
# It has to be a subclass of Enum anyway
enum_type = self.dependencies.get(data_type, data.__class__)
if issubclass(enum_type, Enum):
return Serializer.serialize_enum(data, enum_obj=enum_type)
iter_type = data_type[0] + data_type[-1]
if iter_type in self.serialize_type:
return self.serialize_type[iter_type](
data, data_type[1:-1], **kwargs)
except (ValueError, TypeError) as err:
if (isinstance(err, SerializationError)):
raise err # don't rewrap as SerializationError
msg = "Unable to serialize value: {!r} as type: {!r}."
raise_with_traceback(
SerializationError, msg.format(data, data_type), err)
else:
return self._serialize(data, **kwargs)
@classmethod
def _get_custom_serializers(cls, data_type, **kwargs):
custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type)
if custom_serializer:
return custom_serializer
if kwargs.get("is_xml", False):
return cls._xml_basic_types_serializers.get(data_type)
@classmethod
def serialize_basic(cls, data, data_type, **kwargs):
"""Serialize basic builting data type.
Serializes objects to str, int, float or bool.
Possible kwargs:
- basic_types_serializers dict[str, callable] : If set, use the callable as serializer
- is_xml bool : If set, use xml_basic_types_serializers
:param data: Object to be serialized.
:param str data_type: Type of object in the iterable.
"""
custom_serializer = cls._get_custom_serializers(data_type, **kwargs)
if custom_serializer:
return custom_serializer(data)
if data_type == 'str':
return cls.serialize_unicode(data)
return eval(data_type)(data)
@classmethod
def serialize_unicode(cls, data):
"""Special handling for serializing unicode strings in Py2.
Encode to UTF-8 if unicode, otherwise handle as a str.
:param data: Object to be serialized.
:rtype: str
"""
try: # If I received an enum, return its value
return data.value
except AttributeError:
pass
try:
if isinstance(data, unicode):
# Don't change it, JSON and XML ElementTree are totally able
# to serialize correctly u'' strings
return data
except NameError:
return str(data)
else:
return str(data)
def serialize_iter(self, data, iter_type, div=None, **kwargs):
"""Serialize iterable.
Supported kwargs:
- serialization_ctxt dict : The current entry of _attribute_map, or same format.
serialization_ctxt['type'] should be same as data_type.
- is_xml bool : If set, serialize as XML
:param list attr: Object to be serialized.
:param str iter_type: Type of object in the iterable.
:param bool required: Whether the objects in the iterable must
not be None or empty.
:param str div: If set, this str will be used to combine the elements
in the iterable into a combined string. Default is 'None'.
:rtype: list, str
"""
if isinstance(data, str):
raise SerializationError("Refuse str type as a valid iter type.")
serialization_ctxt = kwargs.get("serialization_ctxt", {})
is_xml = kwargs.get("is_xml", False)
serialized = []
for d in data:
try:
serialized.append(self.serialize_data(d, iter_type, **kwargs))
except ValueError as err:
if isinstance(err, SerializationError):
raise err
serialized.append(None)
if div:
serialized = ['' if s is None else str(s) for s in serialized]
serialized = div.join(serialized)
if 'xml' in serialization_ctxt or is_xml:
# XML serialization is more complicated
xml_desc = serialization_ctxt.get('xml', {})
xml_name = xml_desc.get('name')
if not xml_name:
xml_name = serialization_ctxt['key']
# Create a wrap node if necessary (use the fact that Element and list have "append")
is_wrapped = xml_desc.get("wrapped", False)
node_name = xml_desc.get("itemsName", xml_name)
if is_wrapped:
final_result = _create_xml_node(
xml_name,
xml_desc.get('prefix', None),
xml_desc.get('ns', None)
)
else:
final_result = []
# All list elements to "local_node"
for el in serialized:
if isinstance(el, ET.Element):
el_node = el
else:
el_node = _create_xml_node(
node_name,
xml_desc.get('prefix', None),
xml_desc.get('ns', None)
)
if el is not None: # Otherwise it writes "None" :-p
el_node.text = str(el)
final_result.append(el_node)
return final_result
return serialized
def serialize_dict(self, attr, dict_type, **kwargs):
"""Serialize a dictionary of objects.
:param dict attr: Object to be serialized.
:param str dict_type: Type of object in the dictionary.
:param bool required: Whether the objects in the dictionary must
not be None or empty.
:rtype: dict
"""
serialization_ctxt = kwargs.get("serialization_ctxt", {})
serialized = {}
for key, value in attr.items():
try:
serialized[self.serialize_unicode(key)] = self.serialize_data(
value, dict_type, **kwargs)
except ValueError as err:
if isinstance(err, SerializationError):
raise err
serialized[self.serialize_unicode(key)] = None
if 'xml' in serialization_ctxt:
# XML serialization is more complicated
xml_desc = serialization_ctxt['xml']
xml_name = xml_desc['name']
final_result = _create_xml_node(
xml_name,
xml_desc.get('prefix', None),
xml_desc.get('ns', None)
)
for key, value in serialized.items():
ET.SubElement(final_result, key).text = value
return final_result
return serialized
def serialize_object(self, attr, **kwargs):
"""Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
cast to str.
:param dict attr: Object to be serialized.
:rtype: dict or str
"""
if attr is None:
return None
if isinstance(attr, ET.Element):
return attr
obj_type = type(attr)
if obj_type in self.basic_types:
return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs)
if obj_type is _long_type:
return self.serialize_long(attr)
if obj_type is unicode_str:
return self.serialize_unicode(attr)
if obj_type is datetime.datetime:
return self.serialize_iso(attr)
if obj_type is datetime.date:
return self.serialize_date(attr)
if obj_type is datetime.time:
return self.serialize_time(attr)
if obj_type is datetime.timedelta:
return self.serialize_duration(attr)
if obj_type is decimal.Decimal:
return self.serialize_decimal(attr)
# If it's a model or I know this dependency, serialize as a Model
elif obj_type in self.dependencies.values() or isinstance(attr, Model):
return self._serialize(attr)
if obj_type == dict:
serialized = {}
for key, value in attr.items():
try:
serialized[self.serialize_unicode(key)] = self.serialize_object(
value, **kwargs)
except ValueError:
serialized[self.serialize_unicode(key)] = None
return serialized
if obj_type == list:
serialized = []
for obj in attr:
try:
serialized.append(self.serialize_object(
obj, **kwargs))
except ValueError:
pass
return serialized
return str(attr)
@staticmethod