@autorest/python 6.1.5 → 6.1.7
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.
- package/autorest/__init__.py +10 -3
- package/autorest/black/__init__.py +2 -8
- package/autorest/codegen/__init__.py +4 -2
- package/autorest/codegen/models/__init__.py +1 -1
- package/autorest/codegen/models/base_builder.py +4 -1
- package/autorest/codegen/models/client.py +5 -3
- package/autorest/codegen/models/combined_type.py +6 -4
- package/autorest/codegen/models/enum_type.py +6 -4
- package/autorest/codegen/models/model_type.py +30 -9
- package/autorest/codegen/models/operation.py +32 -0
- package/autorest/codegen/models/operation_group.py +11 -7
- package/autorest/codegen/models/parameter.py +44 -0
- package/autorest/codegen/models/property.py +8 -15
- package/autorest/codegen/models/request_builder_parameter.py +4 -2
- package/autorest/codegen/serializers/__init__.py +18 -2
- package/autorest/codegen/serializers/builder_serializer.py +64 -22
- package/autorest/codegen/serializers/client_serializer.py +3 -4
- package/autorest/codegen/serializers/general_serializer.py +8 -0
- package/autorest/codegen/serializers/model_serializer.py +159 -61
- package/autorest/codegen/templates/model_base.py.jinja2 +636 -0
- package/autorest/codegen/templates/model_container.py.jinja2 +6 -2
- package/autorest/codegen/templates/model_dpg.py.jinja2 +62 -0
- package/autorest/codegen/templates/model_init.py.jinja2 +0 -5
- package/autorest/codegen/templates/{model.py.jinja2 → model_msrest.py.jinja2} +1 -1
- package/autorest/codegen/templates/operation_group.py.jinja2 +1 -1
- package/autorest/codegen/templates/operation_groups_container.py.jinja2 +1 -1
- package/autorest/codegen/templates/validation.py.jinja2 +38 -0
- package/package.json +9 -10
- package/ChangeLog.md +0 -1284
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
# coding=utf-8
|
|
2
|
+
# --------------------------------------------------------------------------
|
|
3
|
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
|
+
# Licensed under the MIT License. See License.txt in the project root for
|
|
5
|
+
# license information.
|
|
6
|
+
# --------------------------------------------------------------------------
|
|
7
|
+
|
|
8
|
+
import functools
|
|
9
|
+
import sys
|
|
10
|
+
import logging
|
|
11
|
+
import base64
|
|
12
|
+
import re
|
|
13
|
+
import isodate
|
|
14
|
+
from json import JSONEncoder
|
|
15
|
+
import typing
|
|
16
|
+
from datetime import datetime, date, time, timedelta
|
|
17
|
+
from azure.core.utils._utils import _FixedOffset
|
|
18
|
+
from collections.abc import MutableMapping
|
|
19
|
+
from azure.core.exceptions import DeserializationError
|
|
20
|
+
import copy
|
|
21
|
+
|
|
22
|
+
_LOGGER = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
__all__ = ["NULL", "AzureJSONEncoder", "Model", "rest_field", "rest_discriminator"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _Null(object):
|
|
28
|
+
"""To create a Falsy object"""
|
|
29
|
+
|
|
30
|
+
def __bool__(self):
|
|
31
|
+
return False
|
|
32
|
+
|
|
33
|
+
__nonzero__ = __bool__ # Python2 compatibility
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
NULL = _Null()
|
|
37
|
+
"""
|
|
38
|
+
A falsy sentinel object which is supposed to be used to specify attributes
|
|
39
|
+
with no data. This gets serialized to `null` on the wire.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _timedelta_as_isostr(td):
|
|
44
|
+
# type: (timedelta) -> str
|
|
45
|
+
"""Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S'
|
|
46
|
+
|
|
47
|
+
Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
# Split seconds to larger units
|
|
51
|
+
seconds = td.total_seconds()
|
|
52
|
+
minutes, seconds = divmod(seconds, 60)
|
|
53
|
+
hours, minutes = divmod(minutes, 60)
|
|
54
|
+
days, hours = divmod(hours, 24)
|
|
55
|
+
|
|
56
|
+
days, hours, minutes = list(map(int, (days, hours, minutes)))
|
|
57
|
+
seconds = round(seconds, 6)
|
|
58
|
+
|
|
59
|
+
# Build date
|
|
60
|
+
date_str = ""
|
|
61
|
+
if days:
|
|
62
|
+
date_str = "%sD" % days
|
|
63
|
+
|
|
64
|
+
# Build time
|
|
65
|
+
time_str = "T"
|
|
66
|
+
|
|
67
|
+
# Hours
|
|
68
|
+
bigger_exists = date_str or hours
|
|
69
|
+
if bigger_exists:
|
|
70
|
+
time_str += "{:02}H".format(hours)
|
|
71
|
+
|
|
72
|
+
# Minutes
|
|
73
|
+
bigger_exists = bigger_exists or minutes
|
|
74
|
+
if bigger_exists:
|
|
75
|
+
time_str += "{:02}M".format(minutes)
|
|
76
|
+
|
|
77
|
+
# Seconds
|
|
78
|
+
try:
|
|
79
|
+
if seconds.is_integer():
|
|
80
|
+
seconds_string = "{:02}".format(int(seconds))
|
|
81
|
+
else:
|
|
82
|
+
# 9 chars long w/ leading 0, 6 digits after decimal
|
|
83
|
+
seconds_string = "%09.6f" % seconds
|
|
84
|
+
# Remove trailing zeros
|
|
85
|
+
seconds_string = seconds_string.rstrip("0")
|
|
86
|
+
except AttributeError: # int.is_integer() raises
|
|
87
|
+
seconds_string = "{:02}".format(seconds)
|
|
88
|
+
|
|
89
|
+
time_str += "{}S".format(seconds_string)
|
|
90
|
+
|
|
91
|
+
return "P" + date_str + time_str
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _datetime_as_isostr(dt):
|
|
95
|
+
# type: (typing.Union[datetime, date, time, timedelta]) -> str
|
|
96
|
+
"""Converts a datetime.(datetime|date|time|timedelta) object into an ISO 8601 formatted string"""
|
|
97
|
+
# First try datetime.datetime
|
|
98
|
+
if hasattr(dt, "year") and hasattr(dt, "hour"):
|
|
99
|
+
dt = typing.cast(datetime, dt)
|
|
100
|
+
# astimezone() fails for naive times in Python 2.7, so make make sure dt is aware (tzinfo is set)
|
|
101
|
+
if not dt.tzinfo:
|
|
102
|
+
iso_formatted = dt.replace(tzinfo=TZ_UTC).isoformat()
|
|
103
|
+
else:
|
|
104
|
+
iso_formatted = dt.astimezone(TZ_UTC).isoformat()
|
|
105
|
+
# Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt)
|
|
106
|
+
return iso_formatted.replace("+00:00", "Z")
|
|
107
|
+
# Next try datetime.date or datetime.time
|
|
108
|
+
try:
|
|
109
|
+
dt = typing.cast(typing.Union[date, time], dt)
|
|
110
|
+
return dt.isoformat()
|
|
111
|
+
# Last, try datetime.timedelta
|
|
112
|
+
except AttributeError:
|
|
113
|
+
dt = typing.cast(timedelta, dt)
|
|
114
|
+
return _timedelta_as_isostr(dt)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
from datetime import timezone
|
|
119
|
+
|
|
120
|
+
TZ_UTC = timezone.utc # type: ignore
|
|
121
|
+
except ImportError:
|
|
122
|
+
TZ_UTC = _FixedOffset(0) # type: ignore
|
|
123
|
+
|
|
124
|
+
def _serialize_bytes(o) -> str:
|
|
125
|
+
return base64.b64encode(o).decode()
|
|
126
|
+
|
|
127
|
+
def _serialize_datetime(o):
|
|
128
|
+
if hasattr(o, "year") and hasattr(o, "hour"):
|
|
129
|
+
# astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set)
|
|
130
|
+
if not o.tzinfo:
|
|
131
|
+
iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat()
|
|
132
|
+
else:
|
|
133
|
+
iso_formatted = o.astimezone(TZ_UTC).isoformat()
|
|
134
|
+
# Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt)
|
|
135
|
+
return iso_formatted.replace("+00:00", "Z")
|
|
136
|
+
# Next try datetime.date or datetime.time
|
|
137
|
+
return o.isoformat()
|
|
138
|
+
|
|
139
|
+
def _is_readonly(p):
|
|
140
|
+
try:
|
|
141
|
+
return p._readonly
|
|
142
|
+
except AttributeError:
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
class AzureJSONEncoder(JSONEncoder):
|
|
146
|
+
"""A JSON encoder that's capable of serializing datetime objects and bytes."""
|
|
147
|
+
|
|
148
|
+
def default(self, o): # pylint: disable=too-many-return-statements
|
|
149
|
+
if _is_model(o):
|
|
150
|
+
readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)]
|
|
151
|
+
return {k: v for k, v in o.items() if k not in readonly_props}
|
|
152
|
+
if isinstance(o, (bytes, bytearray)):
|
|
153
|
+
return base64.b64encode(o).decode()
|
|
154
|
+
try:
|
|
155
|
+
return super(AzureJSONEncoder, self).default(o)
|
|
156
|
+
except TypeError:
|
|
157
|
+
if isinstance(o, (bytes, bytearray)):
|
|
158
|
+
return _serialize_bytes(o)
|
|
159
|
+
try:
|
|
160
|
+
# First try datetime.datetime
|
|
161
|
+
return _serialize_datetime(o)
|
|
162
|
+
except AttributeError:
|
|
163
|
+
pass
|
|
164
|
+
# Last, try datetime.timedelta
|
|
165
|
+
try:
|
|
166
|
+
return _timedelta_as_isostr(o)
|
|
167
|
+
except AttributeError:
|
|
168
|
+
# This will be raised when it hits value.total_seconds in the method above
|
|
169
|
+
pass
|
|
170
|
+
return super(AzureJSONEncoder, self).default(o)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
_VALID_DATE = re.compile(
|
|
174
|
+
r'\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}'
|
|
175
|
+
r'\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?')
|
|
176
|
+
|
|
177
|
+
def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime:
|
|
178
|
+
"""Deserialize ISO-8601 formatted string into Datetime object.
|
|
179
|
+
|
|
180
|
+
:param str attr: response string to be deserialized.
|
|
181
|
+
:rtype: ~datetime.datetime
|
|
182
|
+
"""
|
|
183
|
+
if isinstance(attr, datetime):
|
|
184
|
+
# i'm already deserialized
|
|
185
|
+
return attr
|
|
186
|
+
attr = attr.upper()
|
|
187
|
+
match = _VALID_DATE.match(attr)
|
|
188
|
+
if not match:
|
|
189
|
+
raise ValueError("Invalid datetime string: " + attr)
|
|
190
|
+
|
|
191
|
+
check_decimal = attr.split('.')
|
|
192
|
+
if len(check_decimal) > 1:
|
|
193
|
+
decimal_str = ""
|
|
194
|
+
for digit in check_decimal[1]:
|
|
195
|
+
if digit.isdigit():
|
|
196
|
+
decimal_str += digit
|
|
197
|
+
else:
|
|
198
|
+
break
|
|
199
|
+
if len(decimal_str) > 6:
|
|
200
|
+
attr = attr.replace(decimal_str, decimal_str[0:6])
|
|
201
|
+
|
|
202
|
+
date_obj = isodate.parse_datetime(attr)
|
|
203
|
+
test_utc = date_obj.utctimetuple()
|
|
204
|
+
if test_utc.tm_year > 9999 or test_utc.tm_year < 1:
|
|
205
|
+
raise OverflowError("Hit max or min date")
|
|
206
|
+
return date_obj
|
|
207
|
+
|
|
208
|
+
def _deserialize_date(attr: typing.Union[str, date]) -> date:
|
|
209
|
+
"""Deserialize ISO-8601 formatted string into Date object.
|
|
210
|
+
:param str attr: response string to be deserialized.
|
|
211
|
+
:rtype: Date
|
|
212
|
+
"""
|
|
213
|
+
# This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception.
|
|
214
|
+
if isinstance(attr, date):
|
|
215
|
+
return attr
|
|
216
|
+
return isodate.parse_date(attr, defaultmonth=None, defaultday=None)
|
|
217
|
+
|
|
218
|
+
def _deserialize_time(attr: typing.Union[str, time]) -> time:
|
|
219
|
+
"""Deserialize ISO-8601 formatted string into time object.
|
|
220
|
+
|
|
221
|
+
:param str attr: response string to be deserialized.
|
|
222
|
+
:rtype: datetime.time
|
|
223
|
+
"""
|
|
224
|
+
if isinstance(attr, time):
|
|
225
|
+
return attr
|
|
226
|
+
return isodate.parse_time(attr)
|
|
227
|
+
|
|
228
|
+
def deserialize_bytes(attr):
|
|
229
|
+
return bytes(base64.b64decode(attr))
|
|
230
|
+
|
|
231
|
+
_DESERIALIZE_MAPPING = {
|
|
232
|
+
datetime: _deserialize_datetime,
|
|
233
|
+
date: _deserialize_date,
|
|
234
|
+
time: _deserialize_time,
|
|
235
|
+
bytes: deserialize_bytes,
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
def _get_model(module_name: str, model_name: str):
|
|
239
|
+
module_end = module_name.rsplit('.', 1)[0]
|
|
240
|
+
module = sys.modules[module_end]
|
|
241
|
+
models = {k: v for k, v in module.__dict__.items() if isinstance(v, type)}
|
|
242
|
+
if model_name not in models:
|
|
243
|
+
_LOGGER.warning("Can not find model name in models, will not deserialize")
|
|
244
|
+
return model_name
|
|
245
|
+
return models[model_name]
|
|
246
|
+
|
|
247
|
+
_UNSET = object()
|
|
248
|
+
|
|
249
|
+
class _MyMutableMapping(MutableMapping):
|
|
250
|
+
|
|
251
|
+
def __init__(self, data: typing.Dict[str, typing.Any]) -> None:
|
|
252
|
+
self._data = copy.deepcopy(data)
|
|
253
|
+
|
|
254
|
+
def __contains__(self, key: str) -> bool:
|
|
255
|
+
return key in self._data
|
|
256
|
+
|
|
257
|
+
def __getitem__(self, key: str) -> typing.Any:
|
|
258
|
+
return self._data.__getitem__(key)
|
|
259
|
+
|
|
260
|
+
def __setitem__(self, key: str, value: typing.Any) -> None:
|
|
261
|
+
self._data.__setitem__(key, value)
|
|
262
|
+
|
|
263
|
+
def __delitem__(self, key: str) -> None:
|
|
264
|
+
self._data.__delitem__(key)
|
|
265
|
+
|
|
266
|
+
def __iter__(self) -> typing.Iterator[typing.Any]:
|
|
267
|
+
return self._data.__iter__()
|
|
268
|
+
|
|
269
|
+
def __len__(self) -> int:
|
|
270
|
+
return self._data.__len__()
|
|
271
|
+
|
|
272
|
+
def __ne__(self, other: typing.Any) -> bool:
|
|
273
|
+
return not self.__eq__(other)
|
|
274
|
+
|
|
275
|
+
def keys(self) -> typing.KeysView:
|
|
276
|
+
return self._data.keys()
|
|
277
|
+
|
|
278
|
+
def values(self) -> typing.ValuesView:
|
|
279
|
+
return self._data.values()
|
|
280
|
+
|
|
281
|
+
def items(self) -> typing.ItemsView:
|
|
282
|
+
return self._data.items()
|
|
283
|
+
|
|
284
|
+
def get(self, key: str, default: typing.Any = None) -> typing.Any:
|
|
285
|
+
try:
|
|
286
|
+
return self[key]
|
|
287
|
+
except KeyError:
|
|
288
|
+
return default
|
|
289
|
+
|
|
290
|
+
@typing.overload
|
|
291
|
+
def pop(self, key: str) -> typing.Any:
|
|
292
|
+
...
|
|
293
|
+
|
|
294
|
+
@typing.overload
|
|
295
|
+
def pop(self, key: str, default: typing.Any) -> typing.Any:
|
|
296
|
+
...
|
|
297
|
+
|
|
298
|
+
def pop(self, key: typing.Any, default: typing.Any = _UNSET) -> typing.Any:
|
|
299
|
+
if default is _UNSET:
|
|
300
|
+
return self._data.pop(key)
|
|
301
|
+
return self._data.pop(key, default)
|
|
302
|
+
|
|
303
|
+
def popitem(self) -> typing.Tuple[str, typing.Any]:
|
|
304
|
+
return self._data.popitem()
|
|
305
|
+
|
|
306
|
+
def clear(self) -> None:
|
|
307
|
+
self._data.clear()
|
|
308
|
+
|
|
309
|
+
def update(self, *args: typing.Any, **kwargs: typing.Any) -> None:
|
|
310
|
+
self._data.update(*args, **kwargs)
|
|
311
|
+
|
|
312
|
+
@typing.overload
|
|
313
|
+
def setdefault(self, key: str) -> typing.Any:
|
|
314
|
+
...
|
|
315
|
+
|
|
316
|
+
@typing.overload
|
|
317
|
+
def setdefault(self, key: str, default: typing.Any) -> typing.Any:
|
|
318
|
+
...
|
|
319
|
+
|
|
320
|
+
def setdefault(self, key: typing.Any, default: typing.Any = _UNSET) -> typing.Any:
|
|
321
|
+
if default is _UNSET:
|
|
322
|
+
return self._data.setdefault(key)
|
|
323
|
+
return self._data.setdefault(key, default)
|
|
324
|
+
|
|
325
|
+
def __eq__(self, other: typing.Any) -> bool:
|
|
326
|
+
try:
|
|
327
|
+
other_model = self.__class__(other)
|
|
328
|
+
except Exception:
|
|
329
|
+
return False
|
|
330
|
+
return self._data == other_model._data
|
|
331
|
+
|
|
332
|
+
def __repr__(self) -> str:
|
|
333
|
+
return str(self._data)
|
|
334
|
+
|
|
335
|
+
def _is_model(obj: typing.Any) -> bool:
|
|
336
|
+
return getattr(obj, "_is_model", False)
|
|
337
|
+
|
|
338
|
+
def _serialize(o):
|
|
339
|
+
if isinstance(o, (bytes, bytearray)):
|
|
340
|
+
return _serialize_bytes(o)
|
|
341
|
+
try:
|
|
342
|
+
# First try datetime.datetime
|
|
343
|
+
return _serialize_datetime(o)
|
|
344
|
+
except AttributeError:
|
|
345
|
+
pass
|
|
346
|
+
# Last, try datetime.timedelta
|
|
347
|
+
try:
|
|
348
|
+
return _timedelta_as_isostr(o)
|
|
349
|
+
except AttributeError:
|
|
350
|
+
# This will be raised when it hits value.total_seconds in the method above
|
|
351
|
+
pass
|
|
352
|
+
return o
|
|
353
|
+
|
|
354
|
+
def _get_rest_field(attr_to_rest_field: typing.Dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]:
|
|
355
|
+
try:
|
|
356
|
+
return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name)
|
|
357
|
+
except StopIteration:
|
|
358
|
+
return None
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _create_value(rest_field: typing.Optional["_RestField"], value: typing.Any) -> typing.Any:
|
|
362
|
+
return _deserialize(rest_field._type, value) if (rest_field and rest_field._is_model) else _serialize(value)
|
|
363
|
+
|
|
364
|
+
class Model(_MyMutableMapping):
|
|
365
|
+
_is_model = True
|
|
366
|
+
def __init__(self, *args, **kwargs):
|
|
367
|
+
class_name = self.__class__.__name__
|
|
368
|
+
if len(args) > 1:
|
|
369
|
+
raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given")
|
|
370
|
+
dict_to_pass = {
|
|
371
|
+
rest_field._rest_name: rest_field._default
|
|
372
|
+
for rest_field in self._attr_to_rest_field.values()
|
|
373
|
+
if rest_field._default is not _UNSET
|
|
374
|
+
}
|
|
375
|
+
if args:
|
|
376
|
+
dict_to_pass.update({
|
|
377
|
+
k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v)
|
|
378
|
+
for k, v in args[0].items()
|
|
379
|
+
})
|
|
380
|
+
else:
|
|
381
|
+
non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field]
|
|
382
|
+
if non_attr_kwargs:
|
|
383
|
+
# actual type errors only throw the first wrong keyword arg they see, so following that.
|
|
384
|
+
raise TypeError(
|
|
385
|
+
f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'"
|
|
386
|
+
)
|
|
387
|
+
dict_to_pass.update({
|
|
388
|
+
self._attr_to_rest_field[k]._rest_name: _serialize(v) for k, v in kwargs.items()
|
|
389
|
+
})
|
|
390
|
+
super().__init__(dict_to_pass)
|
|
391
|
+
|
|
392
|
+
def copy(self):
|
|
393
|
+
return Model(self.__dict__)
|
|
394
|
+
|
|
395
|
+
def __new__(cls, *args: typing.Any, **kwargs: typing.Any):
|
|
396
|
+
# we know the last three classes in mro are going to be 'Model', 'dict', and 'object'
|
|
397
|
+
mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order
|
|
398
|
+
attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property
|
|
399
|
+
k: v
|
|
400
|
+
for mro_class in mros
|
|
401
|
+
for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type")
|
|
402
|
+
}
|
|
403
|
+
annotations = {
|
|
404
|
+
k: v
|
|
405
|
+
for mro_class in mros if hasattr(mro_class, '__annotations__')
|
|
406
|
+
for k, v in mro_class.__annotations__.items()
|
|
407
|
+
}
|
|
408
|
+
for attr, rest_field in attr_to_rest_field.items():
|
|
409
|
+
rest_field._module = cls.__module__
|
|
410
|
+
if not rest_field._type:
|
|
411
|
+
rest_field._type = rest_field._get_deserialize_callable_from_annotation(annotations.get(attr, None))
|
|
412
|
+
if not rest_field._rest_name_input:
|
|
413
|
+
rest_field._rest_name_input = attr
|
|
414
|
+
cls._attr_to_rest_field: typing.Dict[str, _RestField] = {
|
|
415
|
+
k: v
|
|
416
|
+
for k, v in attr_to_rest_field.items()
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return super().__new__(cls)
|
|
420
|
+
|
|
421
|
+
def __init_subclass__(cls, discriminator=None):
|
|
422
|
+
for base in cls.__bases__:
|
|
423
|
+
if hasattr(base, '__mapping__'):
|
|
424
|
+
base.__mapping__[discriminator or cls.__name__] = cls
|
|
425
|
+
|
|
426
|
+
@classmethod
|
|
427
|
+
def _get_discriminator(cls) -> typing.Optional[str]:
|
|
428
|
+
for v in cls.__dict__.values():
|
|
429
|
+
if isinstance(v, _RestField) and v._is_discriminator:
|
|
430
|
+
return v._rest_name
|
|
431
|
+
return None
|
|
432
|
+
|
|
433
|
+
@classmethod
|
|
434
|
+
def _deserialize(cls, data):
|
|
435
|
+
if not hasattr(cls, '__mapping__'):
|
|
436
|
+
return cls(data)
|
|
437
|
+
discriminator = cls._get_discriminator()
|
|
438
|
+
mapped_cls = cls.__mapping__.get(data.get(discriminator),cls)
|
|
439
|
+
if mapped_cls == cls:
|
|
440
|
+
return cls(data)
|
|
441
|
+
return mapped_cls._deserialize(data)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _deserialize(deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], value: typing.Any):
|
|
445
|
+
try:
|
|
446
|
+
if value is None:
|
|
447
|
+
return None
|
|
448
|
+
if isinstance(deserializer, type) and issubclass(deserializer, Model):
|
|
449
|
+
return deserializer._deserialize(value)
|
|
450
|
+
return deserializer(value) if deserializer else value
|
|
451
|
+
except Exception as e:
|
|
452
|
+
raise DeserializationError() from e
|
|
453
|
+
|
|
454
|
+
class _RestField:
|
|
455
|
+
def __init__(
|
|
456
|
+
self,
|
|
457
|
+
*,
|
|
458
|
+
name: typing.Optional[str] = None,
|
|
459
|
+
type: typing.Optional[typing.Callable] = None,
|
|
460
|
+
is_discriminator: bool = False,
|
|
461
|
+
readonly: bool = False,
|
|
462
|
+
default: typing.Any = _UNSET,
|
|
463
|
+
):
|
|
464
|
+
self._type = type
|
|
465
|
+
self._rest_name_input = name
|
|
466
|
+
self._module: typing.Optional[str] = None
|
|
467
|
+
self._is_discriminator = is_discriminator
|
|
468
|
+
self._readonly = readonly
|
|
469
|
+
self._is_model = False
|
|
470
|
+
self._default = default
|
|
471
|
+
|
|
472
|
+
@property
|
|
473
|
+
def _rest_name(self) -> str:
|
|
474
|
+
if self._rest_name_input is None:
|
|
475
|
+
raise ValueError("Rest name was never set")
|
|
476
|
+
return self._rest_name_input
|
|
477
|
+
|
|
478
|
+
def __get__(self, obj: Model, type=None):
|
|
479
|
+
# by this point, type and rest_name will have a value bc we default
|
|
480
|
+
# them in __new__ of the Model class
|
|
481
|
+
item = obj.get(self._rest_name)
|
|
482
|
+
if item is None:
|
|
483
|
+
return item
|
|
484
|
+
return _deserialize(self._type, _serialize(item))
|
|
485
|
+
|
|
486
|
+
def __set__(self, obj: Model, value) -> None:
|
|
487
|
+
if value is None:
|
|
488
|
+
# we want to wipe out entries if users set attr to None
|
|
489
|
+
try:
|
|
490
|
+
obj.__delitem__(self._rest_name)
|
|
491
|
+
except KeyError:
|
|
492
|
+
pass
|
|
493
|
+
return
|
|
494
|
+
if self._is_model and not _is_model(value):
|
|
495
|
+
obj.__setitem__(self._rest_name, _deserialize(self._type, value))
|
|
496
|
+
obj.__setitem__(self._rest_name, _serialize(value))
|
|
497
|
+
|
|
498
|
+
def _get_deserialize_callable_from_annotation(self, annotation: typing.Any) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]:
|
|
499
|
+
if not annotation or annotation in [int, float]:
|
|
500
|
+
return None
|
|
501
|
+
|
|
502
|
+
try:
|
|
503
|
+
if _is_model(_get_model(self._module, annotation)):
|
|
504
|
+
self._is_model = True
|
|
505
|
+
def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj):
|
|
506
|
+
if _is_model(obj):
|
|
507
|
+
return obj
|
|
508
|
+
return _deserialize(model_deserializer, obj)
|
|
509
|
+
return functools.partial(_deserialize_model, _get_model(self._module, annotation))
|
|
510
|
+
except Exception:
|
|
511
|
+
pass
|
|
512
|
+
|
|
513
|
+
# is it a literal?
|
|
514
|
+
try:
|
|
515
|
+
if annotation.__origin__ == typing.Literal:
|
|
516
|
+
return None
|
|
517
|
+
except AttributeError:
|
|
518
|
+
pass
|
|
519
|
+
|
|
520
|
+
# is it optional?
|
|
521
|
+
try:
|
|
522
|
+
# right now, assuming we don't have unions, since we're getting rid of the only
|
|
523
|
+
# union we used to have in msrest models, which was union of str and enum
|
|
524
|
+
if any(a for a in annotation.__args__ if a == type(None)):
|
|
525
|
+
|
|
526
|
+
if_obj_deserializer = self._get_deserialize_callable_from_annotation(
|
|
527
|
+
next(a for a in annotation.__args__ if a != type(None)),
|
|
528
|
+
)
|
|
529
|
+
def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj):
|
|
530
|
+
if obj is None:
|
|
531
|
+
return obj
|
|
532
|
+
return _deserialize(if_obj_deserializer, obj)
|
|
533
|
+
|
|
534
|
+
return functools.partial(_deserialize_with_optional, if_obj_deserializer)
|
|
535
|
+
except (AttributeError):
|
|
536
|
+
pass
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
# is it a forward ref / in quotes?
|
|
540
|
+
if isinstance(annotation, str) or type(annotation) == typing.ForwardRef:
|
|
541
|
+
try:
|
|
542
|
+
model_name = annotation.__forward_arg__ # type: ignore
|
|
543
|
+
except AttributeError:
|
|
544
|
+
model_name = annotation
|
|
545
|
+
if self._module is not None:
|
|
546
|
+
annotation = _get_model(self._module, model_name)
|
|
547
|
+
|
|
548
|
+
try:
|
|
549
|
+
if annotation._name == "Dict":
|
|
550
|
+
key_deserializer = self._get_deserialize_callable_from_annotation(annotation.__args__[0])
|
|
551
|
+
value_deserializer = self._get_deserialize_callable_from_annotation(annotation.__args__[1])
|
|
552
|
+
def _deserialize_dict(
|
|
553
|
+
key_deserializer: typing.Optional[typing.Callable],
|
|
554
|
+
value_deserializer: typing.Optional[typing.Callable],
|
|
555
|
+
obj: typing.Dict[typing.Any, typing.Any]
|
|
556
|
+
):
|
|
557
|
+
if obj is None:
|
|
558
|
+
return obj
|
|
559
|
+
return {
|
|
560
|
+
_deserialize(key_deserializer, k): _deserialize(value_deserializer, v)
|
|
561
|
+
for k, v in obj.items()
|
|
562
|
+
}
|
|
563
|
+
return functools.partial(
|
|
564
|
+
_deserialize_dict,
|
|
565
|
+
key_deserializer,
|
|
566
|
+
value_deserializer,
|
|
567
|
+
)
|
|
568
|
+
except (AttributeError, IndexError):
|
|
569
|
+
pass
|
|
570
|
+
try:
|
|
571
|
+
if annotation._name in ["List", "Set", "Tuple", "Sequence"]:
|
|
572
|
+
if len(annotation.__args__) > 1:
|
|
573
|
+
def _deserialize_multiple_sequence(
|
|
574
|
+
entry_deserializers: typing.List[typing.Optional[typing.Callable]],
|
|
575
|
+
obj
|
|
576
|
+
):
|
|
577
|
+
if obj is None:
|
|
578
|
+
return obj
|
|
579
|
+
return type(obj)(
|
|
580
|
+
_deserialize(deserializer, entry)
|
|
581
|
+
for entry, deserializer in zip(obj, entry_deserializers)
|
|
582
|
+
)
|
|
583
|
+
entry_deserializers = [
|
|
584
|
+
self._get_deserialize_callable_from_annotation(dt)
|
|
585
|
+
for dt in annotation.__args__
|
|
586
|
+
]
|
|
587
|
+
return functools.partial(
|
|
588
|
+
_deserialize_multiple_sequence,
|
|
589
|
+
entry_deserializers
|
|
590
|
+
)
|
|
591
|
+
deserializer = self._get_deserialize_callable_from_annotation(annotation.__args__[0])
|
|
592
|
+
def _deserialize_sequence(
|
|
593
|
+
deserializer: typing.Optional[typing.Callable],
|
|
594
|
+
obj,
|
|
595
|
+
):
|
|
596
|
+
if obj is None:
|
|
597
|
+
return obj
|
|
598
|
+
return type(obj)(
|
|
599
|
+
_deserialize(deserializer, entry) for entry in obj
|
|
600
|
+
)
|
|
601
|
+
return functools.partial(
|
|
602
|
+
_deserialize_sequence,
|
|
603
|
+
deserializer
|
|
604
|
+
)
|
|
605
|
+
except (TypeError, IndexError, AttributeError, SyntaxError):
|
|
606
|
+
pass
|
|
607
|
+
|
|
608
|
+
def _deserialize_default(
|
|
609
|
+
annotation,
|
|
610
|
+
deserializer_from_mapping,
|
|
611
|
+
obj,
|
|
612
|
+
):
|
|
613
|
+
if obj is None:
|
|
614
|
+
return obj
|
|
615
|
+
try:
|
|
616
|
+
return _deserialize(annotation, obj)
|
|
617
|
+
except Exception:
|
|
618
|
+
pass
|
|
619
|
+
return _deserialize(deserializer_from_mapping, obj)
|
|
620
|
+
return functools.partial(
|
|
621
|
+
_deserialize_default,
|
|
622
|
+
annotation,
|
|
623
|
+
_DESERIALIZE_MAPPING.get(annotation)
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
def rest_field(
|
|
627
|
+
*,
|
|
628
|
+
name: typing.Optional[str] = None,
|
|
629
|
+
type: typing.Optional[typing.Callable] = None,
|
|
630
|
+
readonly: bool = False,
|
|
631
|
+
default: typing.Any = _UNSET,
|
|
632
|
+
) -> typing.Any:
|
|
633
|
+
return _RestField(name=name, type=type, readonly=readonly, default=default)
|
|
634
|
+
|
|
635
|
+
def rest_discriminator(*, name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None) -> typing.Any:
|
|
636
|
+
return _RestField(name=name, type=type, is_discriminator=True)
|
|
@@ -4,5 +4,9 @@
|
|
|
4
4
|
|
|
5
5
|
{{ imports }}
|
|
6
6
|
{% for model in code_model.model_types %}
|
|
7
|
-
{%
|
|
8
|
-
{%
|
|
7
|
+
{% if code_model.options["models_mode"] == "dpg" %}
|
|
8
|
+
{% include "model_dpg.py.jinja2" %}
|
|
9
|
+
{% else %}
|
|
10
|
+
{% include "model_msrest.py.jinja2" %}
|
|
11
|
+
{% endif %}
|
|
12
|
+
{% endfor %}
|