development-framework-cli 1.7.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. development_framework_cli-1.7.3.dist-info/METADATA +141 -0
  2. development_framework_cli-1.7.3.dist-info/RECORD +71 -0
  3. development_framework_cli-1.7.3.dist-info/WHEEL +4 -0
  4. development_framework_cli-1.7.3.dist-info/entry_points.txt +2 -0
  5. development_framework_cli-1.7.3.dist-info/licenses/LICENSE +21 -0
  6. dm_cli/__init__.py +1 -0
  7. dm_cli/cli.py +180 -0
  8. dm_cli/command_group/__init__.py +0 -0
  9. dm_cli/command_group/data_source.py +176 -0
  10. dm_cli/command_group/entities.py +116 -0
  11. dm_cli/dmss.py +104 -0
  12. dm_cli/dmss_api/__init__.py +27 -0
  13. dm_cli/dmss_api/api/__init__.py +3 -0
  14. dm_cli/dmss_api/api/access_control_api.py +349 -0
  15. dm_cli/dmss_api/api/attribute_api.py +175 -0
  16. dm_cli/dmss_api/api/blob_api.py +344 -0
  17. dm_cli/dmss_api/api/blueprint_api.py +326 -0
  18. dm_cli/dmss_api/api/datasource_api.py +448 -0
  19. dm_cli/dmss_api/api/default_api.py +4439 -0
  20. dm_cli/dmss_api/api/document_api.py +922 -0
  21. dm_cli/dmss_api/api/entity_api.py +464 -0
  22. dm_cli/dmss_api/api/export_api.py +313 -0
  23. dm_cli/dmss_api/api/file_api.py +197 -0
  24. dm_cli/dmss_api/api/health_check_api.py +160 -0
  25. dm_cli/dmss_api/api/lookup_table_api.py +323 -0
  26. dm_cli/dmss_api/api/meta_api.py +185 -0
  27. dm_cli/dmss_api/api/personal_access_token_api.py +433 -0
  28. dm_cli/dmss_api/api/reference_api.py +174 -0
  29. dm_cli/dmss_api/api/search_api.py +183 -0
  30. dm_cli/dmss_api/api/whoami_api.py +163 -0
  31. dm_cli/dmss_api/api_client.py +896 -0
  32. dm_cli/dmss_api/apis/__init__.py +32 -0
  33. dm_cli/dmss_api/configuration.py +482 -0
  34. dm_cli/dmss_api/exceptions.py +158 -0
  35. dm_cli/dmss_api/model/__init__.py +5 -0
  36. dm_cli/dmss_api/model/access_control_list.py +287 -0
  37. dm_cli/dmss_api/model/access_level.py +290 -0
  38. dm_cli/dmss_api/model/acl.py +287 -0
  39. dm_cli/dmss_api/model/data_source_information.py +282 -0
  40. dm_cli/dmss_api/model/data_source_request.py +281 -0
  41. dm_cli/dmss_api/model/dependency.py +294 -0
  42. dm_cli/dmss_api/model/entity.py +275 -0
  43. dm_cli/dmss_api/model/error_response.py +278 -0
  44. dm_cli/dmss_api/model/export_meta_response.py +277 -0
  45. dm_cli/dmss_api/model/get_blueprint_response.py +280 -0
  46. dm_cli/dmss_api/model/lookup.py +283 -0
  47. dm_cli/dmss_api/model/pat_data.py +299 -0
  48. dm_cli/dmss_api/model/recipe.py +311 -0
  49. dm_cli/dmss_api/model/recipe_attribute.py +304 -0
  50. dm_cli/dmss_api/model/reference.py +280 -0
  51. dm_cli/dmss_api/model/reference_entity.py +288 -0
  52. dm_cli/dmss_api/model/repository.py +317 -0
  53. dm_cli/dmss_api/model/repository_type.py +290 -0
  54. dm_cli/dmss_api/model/storage_attribute.py +295 -0
  55. dm_cli/dmss_api/model/storage_data_types.py +292 -0
  56. dm_cli/dmss_api/model/storage_recipe.py +293 -0
  57. dm_cli/dmss_api/model_utils.py +2057 -0
  58. dm_cli/dmss_api/models/__init__.py +29 -0
  59. dm_cli/dmss_api/rest.py +358 -0
  60. dm_cli/domain.py +166 -0
  61. dm_cli/enums.py +48 -0
  62. dm_cli/import_entity.py +128 -0
  63. dm_cli/import_package.py +173 -0
  64. dm_cli/package_tree_from_zip.py +120 -0
  65. dm_cli/state.py +12 -0
  66. dm_cli/utils/__init__.py +0 -0
  67. dm_cli/utils/file_structure.py +31 -0
  68. dm_cli/utils/reference.py +129 -0
  69. dm_cli/utils/resolve_local_ids.py +142 -0
  70. dm_cli/utils/utils.py +161 -0
  71. dm_cli/utils/zip.py +70 -0
@@ -0,0 +1,2057 @@
1
+ """
2
+ Data Modelling Storage Service
3
+
4
+ API for basic data modelling interaction # noqa: E501
5
+
6
+ The version of the OpenAPI document: 1.3.0
7
+ Generated by: https://openapi-generator.tech
8
+ """
9
+
10
+
11
+ import inspect
12
+ import io
13
+ import os
14
+ import pprint
15
+ import re
16
+ import tempfile
17
+ import uuid
18
+ from copy import deepcopy
19
+ from datetime import date, datetime # noqa: F401
20
+
21
+ from dateutil.parser import parse
22
+
23
+ from dm_cli.dmss_api.exceptions import (
24
+ ApiAttributeError,
25
+ ApiKeyError,
26
+ ApiTypeError,
27
+ ApiValueError,
28
+ )
29
+
30
+ none_type = type(None)
31
+ file_type = io.IOBase
32
+
33
+
34
+ def convert_js_args_to_python_args(fn):
35
+ from functools import wraps
36
+ @wraps(fn)
37
+ def wrapped_init(_self, *args, **kwargs):
38
+ """
39
+ An attribute named `self` received from the api will conflicts with the reserved `self`
40
+ parameter of a class method. During generation, `self` attributes are mapped
41
+ to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts.
42
+ """
43
+ spec_property_naming = kwargs.get('_spec_property_naming', False)
44
+ if spec_property_naming:
45
+ kwargs = change_keys_js_to_python(
46
+ kwargs, _self if isinstance(
47
+ _self, type) else _self.__class__)
48
+ return fn(_self, *args, **kwargs)
49
+ return wrapped_init
50
+
51
+
52
+ class cached_property(object):
53
+ # this caches the result of the function call for fn with no inputs
54
+ # use this as a decorator on function methods that you want converted
55
+ # into cached properties
56
+ result_key = '_results'
57
+
58
+ def __init__(self, fn):
59
+ self._fn = fn
60
+
61
+ def __get__(self, instance, cls=None):
62
+ if self.result_key in vars(self):
63
+ return vars(self)[self.result_key]
64
+ else:
65
+ result = self._fn()
66
+ setattr(self, self.result_key, result)
67
+ return result
68
+
69
+
70
+ PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type)
71
+
72
+
73
+ def allows_single_value_input(cls):
74
+ """
75
+ This function returns True if the input composed schema model or any
76
+ descendant model allows a value only input
77
+ This is true for cases where oneOf contains items like:
78
+ oneOf:
79
+ - float
80
+ - NumberWithValidation
81
+ - StringEnum
82
+ - ArrayModel
83
+ - null
84
+ TODO: lru_cache this
85
+ """
86
+ if (
87
+ issubclass(cls, ModelSimple) or
88
+ cls in PRIMITIVE_TYPES
89
+ ):
90
+ return True
91
+ elif issubclass(cls, ModelComposed):
92
+ if not cls._composed_schemas['oneOf']:
93
+ return False
94
+ return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf'])
95
+ return False
96
+
97
+
98
+ def composed_model_input_classes(cls):
99
+ """
100
+ This function returns a list of the possible models that can be accepted as
101
+ inputs.
102
+ TODO: lru_cache this
103
+ """
104
+ if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES:
105
+ return [cls]
106
+ elif issubclass(cls, ModelNormal):
107
+ if cls.discriminator is None:
108
+ return [cls]
109
+ else:
110
+ return get_discriminated_classes(cls)
111
+ elif issubclass(cls, ModelComposed):
112
+ if not cls._composed_schemas['oneOf']:
113
+ return []
114
+ if cls.discriminator is None:
115
+ input_classes = []
116
+ for c in cls._composed_schemas['oneOf']:
117
+ input_classes.extend(composed_model_input_classes(c))
118
+ return input_classes
119
+ else:
120
+ return get_discriminated_classes(cls)
121
+ return []
122
+
123
+
124
+ class OpenApiModel(object):
125
+ """The base class for all OpenAPIModels"""
126
+
127
+ def set_attribute(self, name, value):
128
+ # this is only used to set properties on self
129
+
130
+ path_to_item = []
131
+ if self._path_to_item:
132
+ path_to_item.extend(self._path_to_item)
133
+ path_to_item.append(name)
134
+
135
+ if name in self.openapi_types:
136
+ required_types_mixed = self.openapi_types[name]
137
+ elif self.additional_properties_type is None:
138
+ raise ApiAttributeError(
139
+ "{0} has no attribute '{1}'".format(
140
+ type(self).__name__, name),
141
+ path_to_item
142
+ )
143
+ elif self.additional_properties_type is not None:
144
+ required_types_mixed = self.additional_properties_type
145
+
146
+ if get_simple_class(name) != str:
147
+ error_msg = type_error_message(
148
+ var_name=name,
149
+ var_value=name,
150
+ valid_classes=(str,),
151
+ key_type=True
152
+ )
153
+ raise ApiTypeError(
154
+ error_msg,
155
+ path_to_item=path_to_item,
156
+ valid_classes=(str,),
157
+ key_type=True
158
+ )
159
+
160
+ if self._check_type:
161
+ value = validate_and_convert_types(
162
+ value, required_types_mixed, path_to_item, self._spec_property_naming,
163
+ self._check_type, configuration=self._configuration)
164
+ if (name,) in self.allowed_values:
165
+ check_allowed_values(
166
+ self.allowed_values,
167
+ (name,),
168
+ value
169
+ )
170
+ if (name,) in self.validations:
171
+ check_validations(
172
+ self.validations,
173
+ (name,),
174
+ value,
175
+ self._configuration
176
+ )
177
+ self.__dict__['_data_store'][name] = value
178
+
179
+ def __repr__(self):
180
+ """For `print` and `pprint`"""
181
+ return self.to_str()
182
+
183
+ def __ne__(self, other):
184
+ """Returns true if both objects are not equal"""
185
+ return not self == other
186
+
187
+ def __setattr__(self, attr, value):
188
+ """set the value of an attribute using dot notation: `instance.attr = val`"""
189
+ self[attr] = value
190
+
191
+ def __getattr__(self, attr):
192
+ """get the value of an attribute using dot notation: `instance.attr`"""
193
+ return self.__getitem__(attr)
194
+
195
+ def __copy__(self):
196
+ cls = self.__class__
197
+ if self.get("_spec_property_naming", False):
198
+ return cls._new_from_openapi_data(**self.__dict__)
199
+ else:
200
+ return cls.__new__(cls, **self.__dict__)
201
+
202
+ def __deepcopy__(self, memo):
203
+ cls = self.__class__
204
+
205
+ if self.get("_spec_property_naming", False):
206
+ new_inst = cls._new_from_openapi_data()
207
+ else:
208
+ new_inst = cls.__new__(cls)
209
+
210
+ for k, v in self.__dict__.items():
211
+ setattr(new_inst, k, deepcopy(v, memo))
212
+ return new_inst
213
+
214
+
215
+ def __new__(cls, *args, **kwargs):
216
+ # this function uses the discriminator to
217
+ # pick a new schema/class to instantiate because a discriminator
218
+ # propertyName value was passed in
219
+
220
+ if len(args) == 1:
221
+ arg = args[0]
222
+ if arg is None and is_type_nullable(cls):
223
+ # The input data is the 'null' value and the type is nullable.
224
+ return None
225
+
226
+ if issubclass(cls, ModelComposed) and allows_single_value_input(cls):
227
+ model_kwargs = {}
228
+ oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg)
229
+ return oneof_instance
230
+
231
+ visited_composed_classes = kwargs.get('_visited_composed_classes', ())
232
+ if (
233
+ cls.discriminator is None or
234
+ cls in visited_composed_classes
235
+ ):
236
+ # Use case 1: this openapi schema (cls) does not have a discriminator
237
+ # Use case 2: we have already visited this class before and are sure that we
238
+ # want to instantiate it this time. We have visited this class deserializing
239
+ # a payload with a discriminator. During that process we traveled through
240
+ # this class but did not make an instance of it. Now we are making an
241
+ # instance of a composed class which contains cls in it, so this time make an instance of cls.
242
+ #
243
+ # Here's an example of use case 2: If Animal has a discriminator
244
+ # petType and we pass in "Dog", and the class Dog
245
+ # allOf includes Animal, we move through Animal
246
+ # once using the discriminator, and pick Dog.
247
+ # Then in the composed schema dog Dog, we will make an instance of the
248
+ # Animal class (because Dal has allOf: Animal) but this time we won't travel
249
+ # through Animal's discriminator because we passed in
250
+ # _visited_composed_classes = (Animal,)
251
+
252
+ return super(OpenApiModel, cls).__new__(cls)
253
+
254
+ # Get the name and value of the discriminator property.
255
+ # The discriminator name is obtained from the discriminator meta-data
256
+ # and the discriminator value is obtained from the input data.
257
+ discr_propertyname_py = list(cls.discriminator.keys())[0]
258
+ discr_propertyname_js = cls.attribute_map[discr_propertyname_py]
259
+ if discr_propertyname_js in kwargs:
260
+ discr_value = kwargs[discr_propertyname_js]
261
+ elif discr_propertyname_py in kwargs:
262
+ discr_value = kwargs[discr_propertyname_py]
263
+ else:
264
+ # The input data does not contain the discriminator property.
265
+ path_to_item = kwargs.get('_path_to_item', ())
266
+ raise ApiValueError(
267
+ "Cannot deserialize input data due to missing discriminator. "
268
+ "The discriminator property '%s' is missing at path: %s" %
269
+ (discr_propertyname_js, path_to_item)
270
+ )
271
+
272
+ # Implementation note: the last argument to get_discriminator_class
273
+ # is a list of visited classes. get_discriminator_class may recursively
274
+ # call itself and update the list of visited classes, and the initial
275
+ # value must be an empty list. Hence not using 'visited_composed_classes'
276
+ new_cls = get_discriminator_class(
277
+ cls, discr_propertyname_py, discr_value, [])
278
+ if new_cls is None:
279
+ path_to_item = kwargs.get('_path_to_item', ())
280
+ disc_prop_value = kwargs.get(
281
+ discr_propertyname_js, kwargs.get(discr_propertyname_py))
282
+ raise ApiValueError(
283
+ "Cannot deserialize input data due to invalid discriminator "
284
+ "value. The OpenAPI document has no mapping for discriminator "
285
+ "property '%s'='%s' at path: %s" %
286
+ (discr_propertyname_js, disc_prop_value, path_to_item)
287
+ )
288
+
289
+ if new_cls in visited_composed_classes:
290
+ # if we are making an instance of a composed schema Descendent
291
+ # which allOf includes Ancestor, then Ancestor contains
292
+ # a discriminator that includes Descendent.
293
+ # So if we make an instance of Descendent, we have to make an
294
+ # instance of Ancestor to hold the allOf properties.
295
+ # This code detects that use case and makes the instance of Ancestor
296
+ # For example:
297
+ # When making an instance of Dog, _visited_composed_classes = (Dog,)
298
+ # then we make an instance of Animal to include in dog._composed_instances
299
+ # so when we are here, cls is Animal
300
+ # cls.discriminator != None
301
+ # cls not in _visited_composed_classes
302
+ # new_cls = Dog
303
+ # but we know we know that we already have Dog
304
+ # because it is in visited_composed_classes
305
+ # so make Animal here
306
+ return super(OpenApiModel, cls).__new__(cls)
307
+
308
+ # Build a list containing all oneOf and anyOf descendants.
309
+ oneof_anyof_classes = None
310
+ if cls._composed_schemas is not None:
311
+ oneof_anyof_classes = (
312
+ cls._composed_schemas.get('oneOf', ()) +
313
+ cls._composed_schemas.get('anyOf', ()))
314
+ oneof_anyof_child = new_cls in oneof_anyof_classes
315
+ kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,)
316
+
317
+ if cls._composed_schemas.get('allOf') and oneof_anyof_child:
318
+ # Validate that we can make self because when we make the
319
+ # new_cls it will not include the allOf validations in self
320
+ self_inst = super(OpenApiModel, cls).__new__(cls)
321
+ self_inst.__init__(*args, **kwargs)
322
+
323
+ if kwargs.get("_spec_property_naming", False):
324
+ # when true, implies new is from deserialization
325
+ new_inst = new_cls._new_from_openapi_data(*args, **kwargs)
326
+ else:
327
+ new_inst = new_cls.__new__(new_cls, *args, **kwargs)
328
+ new_inst.__init__(*args, **kwargs)
329
+
330
+ return new_inst
331
+
332
+ @classmethod
333
+ @convert_js_args_to_python_args
334
+ def _new_from_openapi_data(cls, *args, **kwargs):
335
+ # this function uses the discriminator to
336
+ # pick a new schema/class to instantiate because a discriminator
337
+ # propertyName value was passed in
338
+
339
+ if len(args) == 1:
340
+ arg = args[0]
341
+ if arg is None and is_type_nullable(cls):
342
+ # The input data is the 'null' value and the type is nullable.
343
+ return None
344
+
345
+ if issubclass(cls, ModelComposed) and allows_single_value_input(cls):
346
+ model_kwargs = {}
347
+ oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg)
348
+ return oneof_instance
349
+
350
+ visited_composed_classes = kwargs.get('_visited_composed_classes', ())
351
+ if (
352
+ cls.discriminator is None or
353
+ cls in visited_composed_classes
354
+ ):
355
+ # Use case 1: this openapi schema (cls) does not have a discriminator
356
+ # Use case 2: we have already visited this class before and are sure that we
357
+ # want to instantiate it this time. We have visited this class deserializing
358
+ # a payload with a discriminator. During that process we traveled through
359
+ # this class but did not make an instance of it. Now we are making an
360
+ # instance of a composed class which contains cls in it, so this time make an instance of cls.
361
+ #
362
+ # Here's an example of use case 2: If Animal has a discriminator
363
+ # petType and we pass in "Dog", and the class Dog
364
+ # allOf includes Animal, we move through Animal
365
+ # once using the discriminator, and pick Dog.
366
+ # Then in the composed schema dog Dog, we will make an instance of the
367
+ # Animal class (because Dal has allOf: Animal) but this time we won't travel
368
+ # through Animal's discriminator because we passed in
369
+ # _visited_composed_classes = (Animal,)
370
+
371
+ return cls._from_openapi_data(*args, **kwargs)
372
+
373
+ # Get the name and value of the discriminator property.
374
+ # The discriminator name is obtained from the discriminator meta-data
375
+ # and the discriminator value is obtained from the input data.
376
+ discr_propertyname_py = list(cls.discriminator.keys())[0]
377
+ discr_propertyname_js = cls.attribute_map[discr_propertyname_py]
378
+ if discr_propertyname_js in kwargs:
379
+ discr_value = kwargs[discr_propertyname_js]
380
+ elif discr_propertyname_py in kwargs:
381
+ discr_value = kwargs[discr_propertyname_py]
382
+ else:
383
+ # The input data does not contain the discriminator property.
384
+ path_to_item = kwargs.get('_path_to_item', ())
385
+ raise ApiValueError(
386
+ "Cannot deserialize input data due to missing discriminator. "
387
+ "The discriminator property '%s' is missing at path: %s" %
388
+ (discr_propertyname_js, path_to_item)
389
+ )
390
+
391
+ # Implementation note: the last argument to get_discriminator_class
392
+ # is a list of visited classes. get_discriminator_class may recursively
393
+ # call itself and update the list of visited classes, and the initial
394
+ # value must be an empty list. Hence not using 'visited_composed_classes'
395
+ new_cls = get_discriminator_class(
396
+ cls, discr_propertyname_py, discr_value, [])
397
+ if new_cls is None:
398
+ path_to_item = kwargs.get('_path_to_item', ())
399
+ disc_prop_value = kwargs.get(
400
+ discr_propertyname_js, kwargs.get(discr_propertyname_py))
401
+ raise ApiValueError(
402
+ "Cannot deserialize input data due to invalid discriminator "
403
+ "value. The OpenAPI document has no mapping for discriminator "
404
+ "property '%s'='%s' at path: %s" %
405
+ (discr_propertyname_js, disc_prop_value, path_to_item)
406
+ )
407
+
408
+ if new_cls in visited_composed_classes:
409
+ # if we are making an instance of a composed schema Descendent
410
+ # which allOf includes Ancestor, then Ancestor contains
411
+ # a discriminator that includes Descendent.
412
+ # So if we make an instance of Descendent, we have to make an
413
+ # instance of Ancestor to hold the allOf properties.
414
+ # This code detects that use case and makes the instance of Ancestor
415
+ # For example:
416
+ # When making an instance of Dog, _visited_composed_classes = (Dog,)
417
+ # then we make an instance of Animal to include in dog._composed_instances
418
+ # so when we are here, cls is Animal
419
+ # cls.discriminator != None
420
+ # cls not in _visited_composed_classes
421
+ # new_cls = Dog
422
+ # but we know we know that we already have Dog
423
+ # because it is in visited_composed_classes
424
+ # so make Animal here
425
+ return cls._from_openapi_data(*args, **kwargs)
426
+
427
+ # Build a list containing all oneOf and anyOf descendants.
428
+ oneof_anyof_classes = None
429
+ if cls._composed_schemas is not None:
430
+ oneof_anyof_classes = (
431
+ cls._composed_schemas.get('oneOf', ()) +
432
+ cls._composed_schemas.get('anyOf', ()))
433
+ oneof_anyof_child = new_cls in oneof_anyof_classes
434
+ kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,)
435
+
436
+ if cls._composed_schemas.get('allOf') and oneof_anyof_child:
437
+ # Validate that we can make self because when we make the
438
+ # new_cls it will not include the allOf validations in self
439
+ self_inst = cls._from_openapi_data(*args, **kwargs)
440
+
441
+ new_inst = new_cls._new_from_openapi_data(*args, **kwargs)
442
+ return new_inst
443
+
444
+
445
+ class ModelSimple(OpenApiModel):
446
+ """the parent class of models whose type != object in their
447
+ swagger/openapi"""
448
+
449
+ def __setitem__(self, name, value):
450
+ """set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
451
+ if name in self.required_properties:
452
+ self.__dict__[name] = value
453
+ return
454
+
455
+ self.set_attribute(name, value)
456
+
457
+ def get(self, name, default=None):
458
+ """returns the value of an attribute or some default value if the attribute was not set"""
459
+ if name in self.required_properties:
460
+ return self.__dict__[name]
461
+
462
+ return self.__dict__['_data_store'].get(name, default)
463
+
464
+ def __getitem__(self, name):
465
+ """get the value of an attribute using square-bracket notation: `instance[attr]`"""
466
+ if name in self:
467
+ return self.get(name)
468
+
469
+ raise ApiAttributeError(
470
+ "{0} has no attribute '{1}'".format(
471
+ type(self).__name__, name),
472
+ [e for e in [self._path_to_item, name] if e]
473
+ )
474
+
475
+ def __contains__(self, name):
476
+ """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`"""
477
+ if name in self.required_properties:
478
+ return name in self.__dict__
479
+
480
+ return name in self.__dict__['_data_store']
481
+
482
+ def to_str(self):
483
+ """Returns the string representation of the model"""
484
+ return str(self.value)
485
+
486
+ def __eq__(self, other):
487
+ """Returns true if both objects are equal"""
488
+ if not isinstance(other, self.__class__):
489
+ return False
490
+
491
+ this_val = self._data_store['value']
492
+ that_val = other._data_store['value']
493
+ types = set()
494
+ types.add(this_val.__class__)
495
+ types.add(that_val.__class__)
496
+ vals_equal = this_val == that_val
497
+ return vals_equal
498
+
499
+
500
+ class ModelNormal(OpenApiModel):
501
+ """the parent class of models whose type == object in their
502
+ swagger/openapi"""
503
+
504
+ def __setitem__(self, name, value):
505
+ """set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
506
+ if name in self.required_properties:
507
+ self.__dict__[name] = value
508
+ return
509
+
510
+ self.set_attribute(name, value)
511
+
512
+ def get(self, name, default=None):
513
+ """returns the value of an attribute or some default value if the attribute was not set"""
514
+ if name in self.required_properties:
515
+ return self.__dict__[name]
516
+
517
+ return self.__dict__['_data_store'].get(name, default)
518
+
519
+ def __getitem__(self, name):
520
+ """get the value of an attribute using square-bracket notation: `instance[attr]`"""
521
+ if name in self:
522
+ return self.get(name)
523
+
524
+ raise ApiAttributeError(
525
+ "{0} has no attribute '{1}'".format(
526
+ type(self).__name__, name),
527
+ [e for e in [self._path_to_item, name] if e]
528
+ )
529
+
530
+ def __contains__(self, name):
531
+ """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`"""
532
+ if name in self.required_properties:
533
+ return name in self.__dict__
534
+
535
+ return name in self.__dict__['_data_store']
536
+
537
+ def to_dict(self):
538
+ """Returns the model properties as a dict"""
539
+ return model_to_dict(self, serialize=False)
540
+
541
+ def to_str(self):
542
+ """Returns the string representation of the model"""
543
+ return pprint.pformat(self.to_dict())
544
+
545
+ def __eq__(self, other):
546
+ """Returns true if both objects are equal"""
547
+ if not isinstance(other, self.__class__):
548
+ return False
549
+
550
+ if not set(self._data_store.keys()) == set(other._data_store.keys()):
551
+ return False
552
+ for _var_name, this_val in self._data_store.items():
553
+ that_val = other._data_store[_var_name]
554
+ types = set()
555
+ types.add(this_val.__class__)
556
+ types.add(that_val.__class__)
557
+ vals_equal = this_val == that_val
558
+ if not vals_equal:
559
+ return False
560
+ return True
561
+
562
+
563
+ class ModelComposed(OpenApiModel):
564
+ """the parent class of models whose type == object in their
565
+ swagger/openapi and have oneOf/allOf/anyOf
566
+
567
+ When one sets a property we use var_name_to_model_instances to store the value in
568
+ the correct class instances + run any type checking + validation code.
569
+ When one gets a property we use var_name_to_model_instances to get the value
570
+ from the correct class instances.
571
+ This allows multiple composed schemas to contain the same property with additive
572
+ constraints on the value.
573
+
574
+ _composed_schemas (dict) stores the anyOf/allOf/oneOf classes
575
+ key (str): allOf/oneOf/anyOf
576
+ value (list): the classes in the XOf definition.
577
+ Note: none_type can be included when the openapi document version >= 3.1.0
578
+ _composed_instances (list): stores a list of instances of the composed schemas
579
+ defined in _composed_schemas. When properties are accessed in the self instance,
580
+ they are returned from the self._data_store or the data stores in the instances
581
+ in self._composed_schemas
582
+ _var_name_to_model_instances (dict): maps between a variable name on self and
583
+ the composed instances (self included) which contain that data
584
+ key (str): property name
585
+ value (list): list of class instances, self or instances in _composed_instances
586
+ which contain the value that the key is referring to.
587
+ """
588
+
589
+ def __setitem__(self, name, value):
590
+ """set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
591
+ if name in self.required_properties:
592
+ self.__dict__[name] = value
593
+ return
594
+
595
+ """
596
+ Use cases:
597
+ 1. additional_properties_type is None (additionalProperties == False in spec)
598
+ Check for property presence in self.openapi_types
599
+ if not present then throw an error
600
+ if present set in self, set attribute
601
+ always set on composed schemas
602
+ 2. additional_properties_type exists
603
+ set attribute on self
604
+ always set on composed schemas
605
+ """
606
+ if self.additional_properties_type is None:
607
+ """
608
+ For an attribute to exist on a composed schema it must:
609
+ - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND
610
+ - fulfill schema_requirements in each oneOf/anyOf/allOf schemas
611
+
612
+ schema_requirements:
613
+ For an attribute to exist on a schema it must:
614
+ - be present in properties at the schema OR
615
+ - have additionalProperties unset (defaults additionalProperties = any type) OR
616
+ - have additionalProperties set
617
+ """
618
+ if name not in self.openapi_types:
619
+ raise ApiAttributeError(
620
+ "{0} has no attribute '{1}'".format(
621
+ type(self).__name__, name),
622
+ [e for e in [self._path_to_item, name] if e]
623
+ )
624
+ # attribute must be set on self and composed instances
625
+ self.set_attribute(name, value)
626
+ for model_instance in self._composed_instances:
627
+ setattr(model_instance, name, value)
628
+ if name not in self._var_name_to_model_instances:
629
+ # we assigned an additional property
630
+ self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self]
631
+ return None
632
+
633
+ __unset_attribute_value__ = object()
634
+
635
+ def get(self, name, default=None):
636
+ """returns the value of an attribute or some default value if the attribute was not set"""
637
+ if name in self.required_properties:
638
+ return self.__dict__[name]
639
+
640
+ # get the attribute from the correct instance
641
+ model_instances = self._var_name_to_model_instances.get(name)
642
+ values = []
643
+ # A composed model stores self and child (oneof/anyOf/allOf) models under
644
+ # self._var_name_to_model_instances.
645
+ # Any property must exist in self and all model instances
646
+ # The value stored in all model instances must be the same
647
+ if model_instances:
648
+ for model_instance in model_instances:
649
+ if name in model_instance._data_store:
650
+ v = model_instance._data_store[name]
651
+ if v not in values:
652
+ values.append(v)
653
+ len_values = len(values)
654
+ if len_values == 0:
655
+ return default
656
+ elif len_values == 1:
657
+ return values[0]
658
+ elif len_values > 1:
659
+ raise ApiValueError(
660
+ "Values stored for property {0} in {1} differ when looking "
661
+ "at self and self's composed instances. All values must be "
662
+ "the same".format(name, type(self).__name__),
663
+ [e for e in [self._path_to_item, name] if e]
664
+ )
665
+
666
+ def __getitem__(self, name):
667
+ """get the value of an attribute using square-bracket notation: `instance[attr]`"""
668
+ value = self.get(name, self.__unset_attribute_value__)
669
+ if value is self.__unset_attribute_value__:
670
+ raise ApiAttributeError(
671
+ "{0} has no attribute '{1}'".format(
672
+ type(self).__name__, name),
673
+ [e for e in [self._path_to_item, name] if e]
674
+ )
675
+ return value
676
+
677
+ def __contains__(self, name):
678
+ """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`"""
679
+
680
+ if name in self.required_properties:
681
+ return name in self.__dict__
682
+
683
+ model_instances = self._var_name_to_model_instances.get(
684
+ name, self._additional_properties_model_instances)
685
+
686
+ if model_instances:
687
+ for model_instance in model_instances:
688
+ if name in model_instance._data_store:
689
+ return True
690
+
691
+ return False
692
+
693
+ def to_dict(self):
694
+ """Returns the model properties as a dict"""
695
+ return model_to_dict(self, serialize=False)
696
+
697
+ def to_str(self):
698
+ """Returns the string representation of the model"""
699
+ return pprint.pformat(self.to_dict())
700
+
701
+ def __eq__(self, other):
702
+ """Returns true if both objects are equal"""
703
+ if not isinstance(other, self.__class__):
704
+ return False
705
+
706
+ if not set(self._data_store.keys()) == set(other._data_store.keys()):
707
+ return False
708
+ for _var_name, this_val in self._data_store.items():
709
+ that_val = other._data_store[_var_name]
710
+ types = set()
711
+ types.add(this_val.__class__)
712
+ types.add(that_val.__class__)
713
+ vals_equal = this_val == that_val
714
+ if not vals_equal:
715
+ return False
716
+ return True
717
+
718
+
719
+ COERCION_INDEX_BY_TYPE = {
720
+ ModelComposed: 0,
721
+ ModelNormal: 1,
722
+ ModelSimple: 2,
723
+ none_type: 3, # The type of 'None'.
724
+ list: 4,
725
+ dict: 5,
726
+ float: 6,
727
+ int: 7,
728
+ bool: 8,
729
+ datetime: 9,
730
+ date: 10,
731
+ str: 11,
732
+ file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type.
733
+ }
734
+
735
+ # these are used to limit what type conversions we try to do
736
+ # when we have a valid type already and we want to try converting
737
+ # to another type
738
+ UPCONVERSION_TYPE_PAIRS = (
739
+ (str, datetime),
740
+ (str, date),
741
+ # A float may be serialized as an integer, e.g. '3' is a valid serialized float.
742
+ (int, float),
743
+ (list, ModelComposed),
744
+ (dict, ModelComposed),
745
+ (str, ModelComposed),
746
+ (int, ModelComposed),
747
+ (float, ModelComposed),
748
+ (list, ModelComposed),
749
+ (list, ModelNormal),
750
+ (dict, ModelNormal),
751
+ (str, ModelSimple),
752
+ (int, ModelSimple),
753
+ (float, ModelSimple),
754
+ (list, ModelSimple),
755
+ )
756
+
757
+ COERCIBLE_TYPE_PAIRS = {
758
+ False: ( # client instantiation of a model with client data
759
+ # (dict, ModelComposed),
760
+ # (list, ModelComposed),
761
+ # (dict, ModelNormal),
762
+ # (list, ModelNormal),
763
+ # (str, ModelSimple),
764
+ # (int, ModelSimple),
765
+ # (float, ModelSimple),
766
+ # (list, ModelSimple),
767
+ # (str, int),
768
+ # (str, float),
769
+ # (str, datetime),
770
+ # (str, date),
771
+ # (int, str),
772
+ # (float, str),
773
+ ),
774
+ True: ( # server -> client data
775
+ (dict, ModelComposed),
776
+ (list, ModelComposed),
777
+ (dict, ModelNormal),
778
+ (list, ModelNormal),
779
+ (str, ModelSimple),
780
+ (int, ModelSimple),
781
+ (float, ModelSimple),
782
+ (list, ModelSimple),
783
+ # (str, int),
784
+ # (str, float),
785
+ (str, datetime),
786
+ (str, date),
787
+ # (int, str),
788
+ # (float, str),
789
+ (str, file_type)
790
+ ),
791
+ }
792
+
793
+
794
+ def get_simple_class(input_value):
795
+ """Returns an input_value's simple class that we will use for type checking
796
+ Python2:
797
+ float and int will return int, where int is the python3 int backport
798
+ str and unicode will return str, where str is the python3 str backport
799
+ Note: float and int ARE both instances of int backport
800
+ Note: str_py2 and unicode_py2 are NOT both instances of str backport
801
+
802
+ Args:
803
+ input_value (class/class_instance): the item for which we will return
804
+ the simple class
805
+ """
806
+ if isinstance(input_value, type):
807
+ # input_value is a class
808
+ return input_value
809
+ elif isinstance(input_value, tuple):
810
+ return tuple
811
+ elif isinstance(input_value, list):
812
+ return list
813
+ elif isinstance(input_value, dict):
814
+ return dict
815
+ elif isinstance(input_value, none_type):
816
+ return none_type
817
+ elif isinstance(input_value, file_type):
818
+ return file_type
819
+ elif isinstance(input_value, bool):
820
+ # this must be higher than the int check because
821
+ # isinstance(True, int) == True
822
+ return bool
823
+ elif isinstance(input_value, int):
824
+ return int
825
+ elif isinstance(input_value, datetime):
826
+ # this must be higher than the date check because
827
+ # isinstance(datetime_instance, date) == True
828
+ return datetime
829
+ elif isinstance(input_value, date):
830
+ return date
831
+ elif isinstance(input_value, str):
832
+ return str
833
+ return type(input_value)
834
+
835
+
836
+ def check_allowed_values(allowed_values, input_variable_path, input_values):
837
+ """Raises an exception if the input_values are not allowed
838
+
839
+ Args:
840
+ allowed_values (dict): the allowed_values dict
841
+ input_variable_path (tuple): the path to the input variable
842
+ input_values (list/str/int/float/date/datetime): the values that we
843
+ are checking to see if they are in allowed_values
844
+ """
845
+ these_allowed_values = list(allowed_values[input_variable_path].values())
846
+ if (isinstance(input_values, list)
847
+ and not set(input_values).issubset(
848
+ set(these_allowed_values))):
849
+ invalid_values = ", ".join(
850
+ map(str, set(input_values) - set(these_allowed_values))),
851
+ raise ApiValueError(
852
+ "Invalid values for `%s` [%s], must be a subset of [%s]" %
853
+ (
854
+ input_variable_path[0],
855
+ invalid_values,
856
+ ", ".join(map(str, these_allowed_values))
857
+ )
858
+ )
859
+ elif (isinstance(input_values, dict)
860
+ and not set(
861
+ input_values.keys()).issubset(set(these_allowed_values))):
862
+ invalid_values = ", ".join(
863
+ map(str, set(input_values.keys()) - set(these_allowed_values)))
864
+ raise ApiValueError(
865
+ "Invalid keys in `%s` [%s], must be a subset of [%s]" %
866
+ (
867
+ input_variable_path[0],
868
+ invalid_values,
869
+ ", ".join(map(str, these_allowed_values))
870
+ )
871
+ )
872
+ elif (not isinstance(input_values, (list, dict))
873
+ and input_values not in these_allowed_values):
874
+ raise ApiValueError(
875
+ "Invalid value for `%s` (%s), must be one of %s" %
876
+ (
877
+ input_variable_path[0],
878
+ input_values,
879
+ these_allowed_values
880
+ )
881
+ )
882
+
883
+
884
+ def is_json_validation_enabled(schema_keyword, configuration=None):
885
+ """Returns true if JSON schema validation is enabled for the specified
886
+ validation keyword. This can be used to skip JSON schema structural validation
887
+ as requested in the configuration.
888
+
889
+ Args:
890
+ schema_keyword (string): the name of a JSON schema validation keyword.
891
+ configuration (Configuration): the configuration class.
892
+ """
893
+
894
+ return (configuration is None or
895
+ not hasattr(configuration, '_disabled_client_side_validations') or
896
+ schema_keyword not in configuration._disabled_client_side_validations)
897
+
898
+
899
+ def check_validations(
900
+ validations, input_variable_path, input_values,
901
+ configuration=None):
902
+ """Raises an exception if the input_values are invalid
903
+
904
+ Args:
905
+ validations (dict): the validation dictionary.
906
+ input_variable_path (tuple): the path to the input variable.
907
+ input_values (list/str/int/float/date/datetime): the values that we
908
+ are checking.
909
+ configuration (Configuration): the configuration class.
910
+ """
911
+
912
+ if input_values is None:
913
+ return
914
+
915
+ current_validations = validations[input_variable_path]
916
+ if (is_json_validation_enabled('multipleOf', configuration) and
917
+ 'multiple_of' in current_validations and
918
+ isinstance(input_values, (int, float)) and
919
+ not (float(input_values) / current_validations['multiple_of']).is_integer()):
920
+ # Note 'multipleOf' will be as good as the floating point arithmetic.
921
+ raise ApiValueError(
922
+ "Invalid value for `%s`, value must be a multiple of "
923
+ "`%s`" % (
924
+ input_variable_path[0],
925
+ current_validations['multiple_of']
926
+ )
927
+ )
928
+
929
+ if (is_json_validation_enabled('maxLength', configuration) and
930
+ 'max_length' in current_validations and
931
+ len(input_values) > current_validations['max_length']):
932
+ raise ApiValueError(
933
+ "Invalid value for `%s`, length must be less than or equal to "
934
+ "`%s`" % (
935
+ input_variable_path[0],
936
+ current_validations['max_length']
937
+ )
938
+ )
939
+
940
+ if (is_json_validation_enabled('minLength', configuration) and
941
+ 'min_length' in current_validations and
942
+ len(input_values) < current_validations['min_length']):
943
+ raise ApiValueError(
944
+ "Invalid value for `%s`, length must be greater than or equal to "
945
+ "`%s`" % (
946
+ input_variable_path[0],
947
+ current_validations['min_length']
948
+ )
949
+ )
950
+
951
+ if (is_json_validation_enabled('maxItems', configuration) and
952
+ 'max_items' in current_validations and
953
+ len(input_values) > current_validations['max_items']):
954
+ raise ApiValueError(
955
+ "Invalid value for `%s`, number of items must be less than or "
956
+ "equal to `%s`" % (
957
+ input_variable_path[0],
958
+ current_validations['max_items']
959
+ )
960
+ )
961
+
962
+ if (is_json_validation_enabled('minItems', configuration) and
963
+ 'min_items' in current_validations and
964
+ len(input_values) < current_validations['min_items']):
965
+ raise ValueError(
966
+ "Invalid value for `%s`, number of items must be greater than or "
967
+ "equal to `%s`" % (
968
+ input_variable_path[0],
969
+ current_validations['min_items']
970
+ )
971
+ )
972
+
973
+ items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum',
974
+ 'inclusive_minimum')
975
+ if (any(item in current_validations for item in items)):
976
+ if isinstance(input_values, list):
977
+ max_val = max(input_values)
978
+ min_val = min(input_values)
979
+ elif isinstance(input_values, dict):
980
+ max_val = max(input_values.values())
981
+ min_val = min(input_values.values())
982
+ else:
983
+ max_val = input_values
984
+ min_val = input_values
985
+
986
+ if (is_json_validation_enabled('exclusiveMaximum', configuration) and
987
+ 'exclusive_maximum' in current_validations and
988
+ max_val >= current_validations['exclusive_maximum']):
989
+ raise ApiValueError(
990
+ "Invalid value for `%s`, must be a value less than `%s`" % (
991
+ input_variable_path[0],
992
+ current_validations['exclusive_maximum']
993
+ )
994
+ )
995
+
996
+ if (is_json_validation_enabled('maximum', configuration) and
997
+ 'inclusive_maximum' in current_validations and
998
+ max_val > current_validations['inclusive_maximum']):
999
+ raise ApiValueError(
1000
+ "Invalid value for `%s`, must be a value less than or equal to "
1001
+ "`%s`" % (
1002
+ input_variable_path[0],
1003
+ current_validations['inclusive_maximum']
1004
+ )
1005
+ )
1006
+
1007
+ if (is_json_validation_enabled('exclusiveMinimum', configuration) and
1008
+ 'exclusive_minimum' in current_validations and
1009
+ min_val <= current_validations['exclusive_minimum']):
1010
+ raise ApiValueError(
1011
+ "Invalid value for `%s`, must be a value greater than `%s`" %
1012
+ (
1013
+ input_variable_path[0],
1014
+ current_validations['exclusive_maximum']
1015
+ )
1016
+ )
1017
+
1018
+ if (is_json_validation_enabled('minimum', configuration) and
1019
+ 'inclusive_minimum' in current_validations and
1020
+ min_val < current_validations['inclusive_minimum']):
1021
+ raise ApiValueError(
1022
+ "Invalid value for `%s`, must be a value greater than or equal "
1023
+ "to `%s`" % (
1024
+ input_variable_path[0],
1025
+ current_validations['inclusive_minimum']
1026
+ )
1027
+ )
1028
+ flags = current_validations.get('regex', {}).get('flags', 0)
1029
+ if (is_json_validation_enabled('pattern', configuration) and
1030
+ 'regex' in current_validations and
1031
+ not re.search(current_validations['regex']['pattern'],
1032
+ input_values, flags=flags)):
1033
+ err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % (
1034
+ input_variable_path[0],
1035
+ current_validations['regex']['pattern']
1036
+ )
1037
+ if flags != 0:
1038
+ # Don't print the regex flags if the flags are not
1039
+ # specified in the OAS document.
1040
+ err_msg = r"%s with flags=`%s`" % (err_msg, flags)
1041
+ raise ApiValueError(err_msg)
1042
+
1043
+
1044
+ def order_response_types(required_types):
1045
+ """Returns the required types sorted in coercion order
1046
+
1047
+ Args:
1048
+ required_types (list/tuple): collection of classes or instance of
1049
+ list or dict with class information inside it.
1050
+
1051
+ Returns:
1052
+ (list): coercion order sorted collection of classes or instance
1053
+ of list or dict with class information inside it.
1054
+ """
1055
+
1056
+ def index_getter(class_or_instance):
1057
+ if isinstance(class_or_instance, list):
1058
+ return COERCION_INDEX_BY_TYPE[list]
1059
+ elif isinstance(class_or_instance, dict):
1060
+ return COERCION_INDEX_BY_TYPE[dict]
1061
+ elif (inspect.isclass(class_or_instance)
1062
+ and issubclass(class_or_instance, ModelComposed)):
1063
+ return COERCION_INDEX_BY_TYPE[ModelComposed]
1064
+ elif (inspect.isclass(class_or_instance)
1065
+ and issubclass(class_or_instance, ModelNormal)):
1066
+ return COERCION_INDEX_BY_TYPE[ModelNormal]
1067
+ elif (inspect.isclass(class_or_instance)
1068
+ and issubclass(class_or_instance, ModelSimple)):
1069
+ return COERCION_INDEX_BY_TYPE[ModelSimple]
1070
+ elif class_or_instance in COERCION_INDEX_BY_TYPE:
1071
+ return COERCION_INDEX_BY_TYPE[class_or_instance]
1072
+ raise ApiValueError("Unsupported type: %s" % class_or_instance)
1073
+
1074
+ sorted_types = sorted(
1075
+ required_types,
1076
+ key=lambda class_or_instance: index_getter(class_or_instance)
1077
+ )
1078
+ return sorted_types
1079
+
1080
+
1081
+ def remove_uncoercible(required_types_classes, current_item, spec_property_naming,
1082
+ must_convert=True):
1083
+ """Only keeps the type conversions that are possible
1084
+
1085
+ Args:
1086
+ required_types_classes (tuple): tuple of classes that are required
1087
+ these should be ordered by COERCION_INDEX_BY_TYPE
1088
+ spec_property_naming (bool): True if the variable names in the input
1089
+ data are serialized names as specified in the OpenAPI document.
1090
+ False if the variables names in the input data are python
1091
+ variable names in PEP-8 snake case.
1092
+ current_item (any): the current item (input data) to be converted
1093
+
1094
+ Keyword Args:
1095
+ must_convert (bool): if True the item to convert is of the wrong
1096
+ type and we want a big list of coercibles
1097
+ if False, we want a limited list of coercibles
1098
+
1099
+ Returns:
1100
+ (list): the remaining coercible required types, classes only
1101
+ """
1102
+ current_type_simple = get_simple_class(current_item)
1103
+
1104
+ results_classes = []
1105
+ for required_type_class in required_types_classes:
1106
+ # convert our models to OpenApiModel
1107
+ required_type_class_simplified = required_type_class
1108
+ if isinstance(required_type_class_simplified, type):
1109
+ if issubclass(required_type_class_simplified, ModelComposed):
1110
+ required_type_class_simplified = ModelComposed
1111
+ elif issubclass(required_type_class_simplified, ModelNormal):
1112
+ required_type_class_simplified = ModelNormal
1113
+ elif issubclass(required_type_class_simplified, ModelSimple):
1114
+ required_type_class_simplified = ModelSimple
1115
+
1116
+ if required_type_class_simplified == current_type_simple:
1117
+ # don't consider converting to one's own class
1118
+ continue
1119
+
1120
+ class_pair = (current_type_simple, required_type_class_simplified)
1121
+ if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]:
1122
+ results_classes.append(required_type_class)
1123
+ elif class_pair in UPCONVERSION_TYPE_PAIRS:
1124
+ results_classes.append(required_type_class)
1125
+ return results_classes
1126
+
1127
+
1128
+ def get_discriminated_classes(cls):
1129
+ """
1130
+ Returns all the classes that a discriminator converts to
1131
+ TODO: lru_cache this
1132
+ """
1133
+ possible_classes = []
1134
+ key = list(cls.discriminator.keys())[0]
1135
+ if is_type_nullable(cls):
1136
+ possible_classes.append(cls)
1137
+ for discr_cls in cls.discriminator[key].values():
1138
+ if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None:
1139
+ possible_classes.extend(get_discriminated_classes(discr_cls))
1140
+ else:
1141
+ possible_classes.append(discr_cls)
1142
+ return possible_classes
1143
+
1144
+
1145
+ def get_possible_classes(cls, from_server_context):
1146
+ # TODO: lru_cache this
1147
+ possible_classes = [cls]
1148
+ if from_server_context:
1149
+ return possible_classes
1150
+ if hasattr(cls, 'discriminator') and cls.discriminator is not None:
1151
+ possible_classes = []
1152
+ possible_classes.extend(get_discriminated_classes(cls))
1153
+ elif issubclass(cls, ModelComposed):
1154
+ possible_classes.extend(composed_model_input_classes(cls))
1155
+ return possible_classes
1156
+
1157
+
1158
+ def get_required_type_classes(required_types_mixed, spec_property_naming):
1159
+ """Converts the tuple required_types into a tuple and a dict described
1160
+ below
1161
+
1162
+ Args:
1163
+ required_types_mixed (tuple/list): will contain either classes or
1164
+ instance of list or dict
1165
+ spec_property_naming (bool): if True these values came from the
1166
+ server, and we use the data types in our endpoints.
1167
+ If False, we are client side and we need to include
1168
+ oneOf and discriminator classes inside the data types in our endpoints
1169
+
1170
+ Returns:
1171
+ (valid_classes, dict_valid_class_to_child_types_mixed):
1172
+ valid_classes (tuple): the valid classes that the current item
1173
+ should be
1174
+ dict_valid_class_to_child_types_mixed (dict):
1175
+ valid_class (class): this is the key
1176
+ child_types_mixed (list/dict/tuple): describes the valid child
1177
+ types
1178
+ """
1179
+ valid_classes = []
1180
+ child_req_types_by_current_type = {}
1181
+ for required_type in required_types_mixed:
1182
+ if isinstance(required_type, list):
1183
+ valid_classes.append(list)
1184
+ child_req_types_by_current_type[list] = required_type
1185
+ elif isinstance(required_type, tuple):
1186
+ valid_classes.append(tuple)
1187
+ child_req_types_by_current_type[tuple] = required_type
1188
+ elif isinstance(required_type, dict):
1189
+ valid_classes.append(dict)
1190
+ child_req_types_by_current_type[dict] = required_type[str]
1191
+ else:
1192
+ valid_classes.extend(get_possible_classes(required_type, spec_property_naming))
1193
+ return tuple(valid_classes), child_req_types_by_current_type
1194
+
1195
+
1196
+ def change_keys_js_to_python(input_dict, model_class):
1197
+ """
1198
+ Converts from javascript_key keys in the input_dict to python_keys in
1199
+ the output dict using the mapping in model_class.
1200
+ If the input_dict contains a key which does not declared in the model_class,
1201
+ the key is added to the output dict as is. The assumption is the model_class
1202
+ may have undeclared properties (additionalProperties attribute in the OAS
1203
+ document).
1204
+ """
1205
+
1206
+ if getattr(model_class, 'attribute_map', None) is None:
1207
+ return input_dict
1208
+ output_dict = {}
1209
+ reversed_attr_map = {value: key for key, value in
1210
+ model_class.attribute_map.items()}
1211
+ for javascript_key, value in input_dict.items():
1212
+ python_key = reversed_attr_map.get(javascript_key)
1213
+ if python_key is None:
1214
+ # if the key is unknown, it is in error or it is an
1215
+ # additionalProperties variable
1216
+ python_key = javascript_key
1217
+ output_dict[python_key] = value
1218
+ return output_dict
1219
+
1220
+
1221
+ def get_type_error(var_value, path_to_item, valid_classes, key_type=False):
1222
+ error_msg = type_error_message(
1223
+ var_name=path_to_item[-1],
1224
+ var_value=var_value,
1225
+ valid_classes=valid_classes,
1226
+ key_type=key_type
1227
+ )
1228
+ return ApiTypeError(
1229
+ error_msg,
1230
+ path_to_item=path_to_item,
1231
+ valid_classes=valid_classes,
1232
+ key_type=key_type
1233
+ )
1234
+
1235
+
1236
+ def deserialize_primitive(data, klass, path_to_item):
1237
+ """Deserializes string to primitive type.
1238
+
1239
+ :param data: str/int/float
1240
+ :param klass: str/class the class to convert to
1241
+
1242
+ :return: int, float, str, bool, date, datetime
1243
+ """
1244
+ additional_message = ""
1245
+ try:
1246
+ if klass in {datetime, date}:
1247
+ additional_message = (
1248
+ "If you need your parameter to have a fallback "
1249
+ "string value, please set its type as `type: {}` in your "
1250
+ "spec. That allows the value to be any type. "
1251
+ )
1252
+ if klass == datetime:
1253
+ if len(data) < 8:
1254
+ raise ValueError("This is not a datetime")
1255
+ # The string should be in iso8601 datetime format.
1256
+ parsed_datetime = parse(data)
1257
+ date_only = (
1258
+ parsed_datetime.hour == 0 and
1259
+ parsed_datetime.minute == 0 and
1260
+ parsed_datetime.second == 0 and
1261
+ parsed_datetime.tzinfo is None and
1262
+ 8 <= len(data) <= 10
1263
+ )
1264
+ if date_only:
1265
+ raise ValueError("This is a date, not a datetime")
1266
+ return parsed_datetime
1267
+ elif klass == date:
1268
+ if len(data) < 8:
1269
+ raise ValueError("This is not a date")
1270
+ return parse(data).date()
1271
+ else:
1272
+ converted_value = klass(data)
1273
+ if isinstance(data, str) and klass == float:
1274
+ if str(converted_value) != data:
1275
+ # '7' -> 7.0 -> '7.0' != '7'
1276
+ raise ValueError('This is not a float')
1277
+ return converted_value
1278
+ except (OverflowError, ValueError) as ex:
1279
+ # parse can raise OverflowError
1280
+ raise ApiValueError(
1281
+ "{0}Failed to parse {1} as {2}".format(
1282
+ additional_message, repr(data), klass.__name__
1283
+ ),
1284
+ path_to_item=path_to_item
1285
+ ) from ex
1286
+
1287
+
1288
+ def get_discriminator_class(model_class,
1289
+ discr_name,
1290
+ discr_value, cls_visited):
1291
+ """Returns the child class specified by the discriminator.
1292
+
1293
+ Args:
1294
+ model_class (OpenApiModel): the model class.
1295
+ discr_name (string): the name of the discriminator property.
1296
+ discr_value (any): the discriminator value.
1297
+ cls_visited (list): list of model classes that have been visited.
1298
+ Used to determine the discriminator class without
1299
+ visiting circular references indefinitely.
1300
+
1301
+ Returns:
1302
+ used_model_class (class/None): the chosen child class that will be used
1303
+ to deserialize the data, for example dog.Dog.
1304
+ If a class is not found, None is returned.
1305
+ """
1306
+
1307
+ if model_class in cls_visited:
1308
+ # The class has already been visited and no suitable class was found.
1309
+ return None
1310
+ cls_visited.append(model_class)
1311
+ used_model_class = None
1312
+ if discr_name in model_class.discriminator:
1313
+ class_name_to_discr_class = model_class.discriminator[discr_name]
1314
+ used_model_class = class_name_to_discr_class.get(discr_value)
1315
+ if used_model_class is None:
1316
+ # We didn't find a discriminated class in class_name_to_discr_class.
1317
+ # So look in the ancestor or descendant discriminators
1318
+ # The discriminator mapping may exist in a descendant (anyOf, oneOf)
1319
+ # or ancestor (allOf).
1320
+ # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat
1321
+ # hierarchy, the discriminator mappings may be defined at any level
1322
+ # in the hierarchy.
1323
+ # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig
1324
+ # if we try to make BasquePig from mammal, we need to travel through
1325
+ # the oneOf descendant discriminators to find BasquePig
1326
+ descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \
1327
+ model_class._composed_schemas.get('anyOf', ())
1328
+ ancestor_classes = model_class._composed_schemas.get('allOf', ())
1329
+ possible_classes = descendant_classes + ancestor_classes
1330
+ for cls in possible_classes:
1331
+ # Check if the schema has inherited discriminators.
1332
+ if hasattr(cls, 'discriminator') and cls.discriminator is not None:
1333
+ used_model_class = get_discriminator_class(
1334
+ cls, discr_name, discr_value, cls_visited)
1335
+ if used_model_class is not None:
1336
+ return used_model_class
1337
+ return used_model_class
1338
+
1339
+
1340
+ def deserialize_model(model_data, model_class, path_to_item, check_type,
1341
+ configuration, spec_property_naming):
1342
+ """Deserializes model_data to model instance.
1343
+
1344
+ Args:
1345
+ model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model
1346
+ model_class (OpenApiModel): the model class
1347
+ path_to_item (list): path to the model in the received data
1348
+ check_type (bool): whether to check the data tupe for the values in
1349
+ the model
1350
+ configuration (Configuration): the instance to use to convert files
1351
+ spec_property_naming (bool): True if the variable names in the input
1352
+ data are serialized names as specified in the OpenAPI document.
1353
+ False if the variables names in the input data are python
1354
+ variable names in PEP-8 snake case.
1355
+
1356
+ Returns:
1357
+ model instance
1358
+
1359
+ Raise:
1360
+ ApiTypeError
1361
+ ApiValueError
1362
+ ApiKeyError
1363
+ """
1364
+
1365
+ kw_args = dict(_check_type=check_type,
1366
+ _path_to_item=path_to_item,
1367
+ _configuration=configuration,
1368
+ _spec_property_naming=spec_property_naming)
1369
+
1370
+ if issubclass(model_class, ModelSimple):
1371
+ return model_class._new_from_openapi_data(model_data, **kw_args)
1372
+ elif isinstance(model_data, list):
1373
+ return model_class._new_from_openapi_data(*model_data, **kw_args)
1374
+ if isinstance(model_data, dict):
1375
+ kw_args.update(model_data)
1376
+ return model_class._new_from_openapi_data(**kw_args)
1377
+ elif isinstance(model_data, PRIMITIVE_TYPES):
1378
+ return model_class._new_from_openapi_data(model_data, **kw_args)
1379
+
1380
+
1381
+ def deserialize_file(response_data, configuration, content_disposition=None):
1382
+ """Deserializes body to file
1383
+
1384
+ Saves response body into a file in a temporary folder,
1385
+ using the filename from the `Content-Disposition` header if provided.
1386
+
1387
+ Args:
1388
+ param response_data (str): the file data to write
1389
+ configuration (Configuration): the instance to use to convert files
1390
+
1391
+ Keyword Args:
1392
+ content_disposition (str): the value of the Content-Disposition
1393
+ header
1394
+
1395
+ Returns:
1396
+ (file_type): the deserialized file which is open
1397
+ The user is responsible for closing and reading the file
1398
+ """
1399
+ fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path)
1400
+ os.close(fd)
1401
+ os.remove(path)
1402
+
1403
+ if content_disposition:
1404
+ filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
1405
+ content_disposition,
1406
+ flags=re.I)
1407
+ if filename is not None:
1408
+ filename = filename.group(1)
1409
+ else:
1410
+ filename = "default_" + str(uuid.uuid4())
1411
+
1412
+ path = os.path.join(os.path.dirname(path), filename)
1413
+
1414
+ with open(path, "wb") as f:
1415
+ if isinstance(response_data, str):
1416
+ # change str to bytes so we can write it
1417
+ response_data = response_data.encode('utf-8')
1418
+ f.write(response_data)
1419
+
1420
+ f = open(path, "rb")
1421
+ return f
1422
+
1423
+
1424
+ def attempt_convert_item(input_value, valid_classes, path_to_item,
1425
+ configuration, spec_property_naming, key_type=False,
1426
+ must_convert=False, check_type=True):
1427
+ """
1428
+ Args:
1429
+ input_value (any): the data to convert
1430
+ valid_classes (any): the classes that are valid
1431
+ path_to_item (list): the path to the item to convert
1432
+ configuration (Configuration): the instance to use to convert files
1433
+ spec_property_naming (bool): True if the variable names in the input
1434
+ data are serialized names as specified in the OpenAPI document.
1435
+ False if the variables names in the input data are python
1436
+ variable names in PEP-8 snake case.
1437
+ key_type (bool): if True we need to convert a key type (not supported)
1438
+ must_convert (bool): if True we must convert
1439
+ check_type (bool): if True we check the type or the returned data in
1440
+ ModelComposed/ModelNormal/ModelSimple instances
1441
+
1442
+ Returns:
1443
+ instance (any) the fixed item
1444
+
1445
+ Raises:
1446
+ ApiTypeError
1447
+ ApiValueError
1448
+ ApiKeyError
1449
+ """
1450
+ valid_classes_ordered = order_response_types(valid_classes)
1451
+ valid_classes_coercible = remove_uncoercible(
1452
+ valid_classes_ordered, input_value, spec_property_naming)
1453
+ if not valid_classes_coercible or key_type:
1454
+ # we do not handle keytype errors, json will take care
1455
+ # of this for us
1456
+ if configuration is None or not configuration.discard_unknown_keys:
1457
+ raise get_type_error(input_value, path_to_item, valid_classes,
1458
+ key_type=key_type)
1459
+ for valid_class in valid_classes_coercible:
1460
+ try:
1461
+ if issubclass(valid_class, OpenApiModel):
1462
+ return deserialize_model(input_value, valid_class,
1463
+ path_to_item, check_type,
1464
+ configuration, spec_property_naming)
1465
+ elif valid_class == file_type:
1466
+ return deserialize_file(input_value, configuration)
1467
+ return deserialize_primitive(input_value, valid_class,
1468
+ path_to_item)
1469
+ except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc:
1470
+ if must_convert:
1471
+ raise conversion_exc
1472
+ # if we have conversion errors when must_convert == False
1473
+ # we ignore the exception and move on to the next class
1474
+ continue
1475
+ # we were unable to convert, must_convert == False
1476
+ return input_value
1477
+
1478
+
1479
+ def is_type_nullable(input_type):
1480
+ """
1481
+ Returns true if None is an allowed value for the specified input_type.
1482
+
1483
+ A type is nullable if at least one of the following conditions is true:
1484
+ 1. The OAS 'nullable' attribute has been specified,
1485
+ 1. The type is the 'null' type,
1486
+ 1. The type is a anyOf/oneOf composed schema, and a child schema is
1487
+ the 'null' type.
1488
+ Args:
1489
+ input_type (type): the class of the input_value that we are
1490
+ checking
1491
+ Returns:
1492
+ bool
1493
+ """
1494
+ if input_type is none_type:
1495
+ return True
1496
+ if issubclass(input_type, OpenApiModel) and input_type._nullable:
1497
+ return True
1498
+ if issubclass(input_type, ModelComposed):
1499
+ # If oneOf/anyOf, check if the 'null' type is one of the allowed types.
1500
+ for t in input_type._composed_schemas.get('oneOf', ()):
1501
+ if is_type_nullable(t):
1502
+ return True
1503
+ for t in input_type._composed_schemas.get('anyOf', ()):
1504
+ if is_type_nullable(t):
1505
+ return True
1506
+ return False
1507
+
1508
+
1509
+ def is_valid_type(input_class_simple, valid_classes):
1510
+ """
1511
+ Args:
1512
+ input_class_simple (class): the class of the input_value that we are
1513
+ checking
1514
+ valid_classes (tuple): the valid classes that the current item
1515
+ should be
1516
+ Returns:
1517
+ bool
1518
+ """
1519
+ if issubclass(input_class_simple, OpenApiModel) and \
1520
+ valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,):
1521
+ return True
1522
+ valid_type = input_class_simple in valid_classes
1523
+ if not valid_type and (
1524
+ issubclass(input_class_simple, OpenApiModel) or
1525
+ input_class_simple is none_type):
1526
+ for valid_class in valid_classes:
1527
+ if input_class_simple is none_type and is_type_nullable(valid_class):
1528
+ # Schema is oneOf/anyOf and the 'null' type is one of the allowed types.
1529
+ return True
1530
+ if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator):
1531
+ continue
1532
+ discr_propertyname_py = list(valid_class.discriminator.keys())[0]
1533
+ discriminator_classes = (
1534
+ valid_class.discriminator[discr_propertyname_py].values()
1535
+ )
1536
+ valid_type = is_valid_type(input_class_simple, discriminator_classes)
1537
+ if valid_type:
1538
+ return True
1539
+ return valid_type
1540
+
1541
+
1542
+ def validate_and_convert_types(input_value, required_types_mixed, path_to_item,
1543
+ spec_property_naming, _check_type, configuration=None):
1544
+ """Raises a TypeError is there is a problem, otherwise returns value
1545
+
1546
+ Args:
1547
+ input_value (any): the data to validate/convert
1548
+ required_types_mixed (list/dict/tuple): A list of
1549
+ valid classes, or a list tuples of valid classes, or a dict where
1550
+ the value is a tuple of value classes
1551
+ path_to_item: (list) the path to the data being validated
1552
+ this stores a list of keys or indices to get to the data being
1553
+ validated
1554
+ spec_property_naming (bool): True if the variable names in the input
1555
+ data are serialized names as specified in the OpenAPI document.
1556
+ False if the variables names in the input data are python
1557
+ variable names in PEP-8 snake case.
1558
+ _check_type: (boolean) if true, type will be checked and conversion
1559
+ will be attempted.
1560
+ configuration: (Configuration): the configuration class to use
1561
+ when converting file_type items.
1562
+ If passed, conversion will be attempted when possible
1563
+ If not passed, no conversions will be attempted and
1564
+ exceptions will be raised
1565
+
1566
+ Returns:
1567
+ the correctly typed value
1568
+
1569
+ Raises:
1570
+ ApiTypeError
1571
+ """
1572
+ results = get_required_type_classes(required_types_mixed, spec_property_naming)
1573
+ valid_classes, child_req_types_by_current_type = results
1574
+
1575
+ input_class_simple = get_simple_class(input_value)
1576
+ valid_type = is_valid_type(input_class_simple, valid_classes)
1577
+ if not valid_type:
1578
+ if (configuration
1579
+ or (input_class_simple == dict
1580
+ and dict not in valid_classes)):
1581
+ # if input_value is not valid_type try to convert it
1582
+ converted_instance = attempt_convert_item(
1583
+ input_value,
1584
+ valid_classes,
1585
+ path_to_item,
1586
+ configuration,
1587
+ spec_property_naming,
1588
+ key_type=False,
1589
+ must_convert=True,
1590
+ check_type=_check_type
1591
+ )
1592
+ return converted_instance
1593
+ else:
1594
+ raise get_type_error(input_value, path_to_item, valid_classes,
1595
+ key_type=False)
1596
+
1597
+ if child_req_types_by_current_type == {}:
1598
+ # all types are of the required types and there are no more inner
1599
+ # variables left to look at
1600
+ return input_value
1601
+
1602
+ # input_value's type is in valid_classes
1603
+ if len(valid_classes) > 1 and configuration:
1604
+ # there are valid classes which are not the current class
1605
+ valid_classes_coercible = remove_uncoercible(
1606
+ valid_classes, input_value, spec_property_naming, must_convert=False)
1607
+ if valid_classes_coercible:
1608
+ converted_instance = attempt_convert_item(
1609
+ input_value,
1610
+ valid_classes_coercible,
1611
+ path_to_item,
1612
+ configuration,
1613
+ spec_property_naming,
1614
+ key_type=False,
1615
+ must_convert=False,
1616
+ check_type=_check_type
1617
+ )
1618
+ return converted_instance
1619
+
1620
+ inner_required_types = child_req_types_by_current_type.get(
1621
+ type(input_value)
1622
+ )
1623
+ if inner_required_types is None:
1624
+ # for this type, there are not more inner variables left to look at
1625
+ return input_value
1626
+ if isinstance(input_value, list):
1627
+ if input_value == []:
1628
+ # allow an empty list
1629
+ return input_value
1630
+ for index, inner_value in enumerate(input_value):
1631
+ inner_path = list(path_to_item)
1632
+ inner_path.append(index)
1633
+ input_value[index] = validate_and_convert_types(
1634
+ inner_value,
1635
+ inner_required_types,
1636
+ inner_path,
1637
+ spec_property_naming,
1638
+ _check_type,
1639
+ configuration=configuration
1640
+ )
1641
+ elif isinstance(input_value, dict):
1642
+ if input_value == {}:
1643
+ # allow an empty dict
1644
+ return input_value
1645
+ for inner_key, inner_val in input_value.items():
1646
+ inner_path = list(path_to_item)
1647
+ inner_path.append(inner_key)
1648
+ if get_simple_class(inner_key) != str:
1649
+ raise get_type_error(inner_key, inner_path, valid_classes,
1650
+ key_type=True)
1651
+ input_value[inner_key] = validate_and_convert_types(
1652
+ inner_val,
1653
+ inner_required_types,
1654
+ inner_path,
1655
+ spec_property_naming,
1656
+ _check_type,
1657
+ configuration=configuration
1658
+ )
1659
+ return input_value
1660
+
1661
+
1662
+ def model_to_dict(model_instance, serialize=True):
1663
+ """Returns the model properties as a dict
1664
+
1665
+ Args:
1666
+ model_instance (one of your model instances): the model instance that
1667
+ will be converted to a dict.
1668
+
1669
+ Keyword Args:
1670
+ serialize (bool): if True, the keys in the dict will be values from
1671
+ attribute_map
1672
+ """
1673
+ result = {}
1674
+
1675
+ def extract_item(item): return (
1676
+ item[0], model_to_dict(
1677
+ item[1], serialize=serialize)) if hasattr(
1678
+ item[1], '_data_store') else item
1679
+
1680
+ model_instances = [model_instance]
1681
+ if model_instance._composed_schemas:
1682
+ model_instances.extend(model_instance._composed_instances)
1683
+ seen_json_attribute_names = set()
1684
+ used_fallback_python_attribute_names = set()
1685
+ py_to_json_map = {}
1686
+ for model_instance in model_instances:
1687
+ for attr, value in model_instance._data_store.items():
1688
+ if serialize:
1689
+ # we use get here because additional property key names do not
1690
+ # exist in attribute_map
1691
+ try:
1692
+ attr = model_instance.attribute_map[attr]
1693
+ py_to_json_map.update(model_instance.attribute_map)
1694
+ seen_json_attribute_names.add(attr)
1695
+ except KeyError:
1696
+ used_fallback_python_attribute_names.add(attr)
1697
+ if isinstance(value, list):
1698
+ if not value:
1699
+ # empty list or None
1700
+ result[attr] = value
1701
+ else:
1702
+ res = []
1703
+ for v in value:
1704
+ if isinstance(v, PRIMITIVE_TYPES) or v is None:
1705
+ res.append(v)
1706
+ elif isinstance(v, ModelSimple):
1707
+ res.append(v.value)
1708
+ elif isinstance(v, dict):
1709
+ res.append(dict(map(
1710
+ extract_item,
1711
+ v.items()
1712
+ )))
1713
+ else:
1714
+ res.append(model_to_dict(v, serialize=serialize))
1715
+ result[attr] = res
1716
+ elif isinstance(value, dict):
1717
+ result[attr] = dict(map(
1718
+ extract_item,
1719
+ value.items()
1720
+ ))
1721
+ elif isinstance(value, ModelSimple):
1722
+ result[attr] = value.value
1723
+ elif hasattr(value, '_data_store'):
1724
+ result[attr] = model_to_dict(value, serialize=serialize)
1725
+ else:
1726
+ result[attr] = value
1727
+ if serialize:
1728
+ for python_key in used_fallback_python_attribute_names:
1729
+ json_key = py_to_json_map.get(python_key)
1730
+ if json_key is None:
1731
+ continue
1732
+ if python_key == json_key:
1733
+ continue
1734
+ json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names
1735
+ if json_key_assigned_no_need_for_python_key:
1736
+ del result[python_key]
1737
+
1738
+ return result
1739
+
1740
+
1741
+ def type_error_message(var_value=None, var_name=None, valid_classes=None,
1742
+ key_type=None):
1743
+ """
1744
+ Keyword Args:
1745
+ var_value (any): the variable which has the type_error
1746
+ var_name (str): the name of the variable which has the typ error
1747
+ valid_classes (tuple): the accepted classes for current_item's
1748
+ value
1749
+ key_type (bool): False if our value is a value in a dict
1750
+ True if it is a key in a dict
1751
+ False if our item is an item in a list
1752
+ """
1753
+ key_or_value = 'value'
1754
+ if key_type:
1755
+ key_or_value = 'key'
1756
+ valid_classes_phrase = get_valid_classes_phrase(valid_classes)
1757
+ msg = (
1758
+ "Invalid type for variable '{0}'. Required {1} type {2} and "
1759
+ "passed type was {3}".format(
1760
+ var_name,
1761
+ key_or_value,
1762
+ valid_classes_phrase,
1763
+ type(var_value).__name__,
1764
+ )
1765
+ )
1766
+ return msg
1767
+
1768
+
1769
+ def get_valid_classes_phrase(input_classes):
1770
+ """Returns a string phrase describing what types are allowed
1771
+ """
1772
+ all_classes = list(input_classes)
1773
+ all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
1774
+ all_class_names = [cls.__name__ for cls in all_classes]
1775
+ if len(all_class_names) == 1:
1776
+ return 'is {0}'.format(all_class_names[0])
1777
+ return "is one of [{0}]".format(", ".join(all_class_names))
1778
+
1779
+
1780
+ def get_allof_instances(self, model_args, constant_args):
1781
+ """
1782
+ Args:
1783
+ self: the class we are handling
1784
+ model_args (dict): var_name to var_value
1785
+ used to make instances
1786
+ constant_args (dict):
1787
+ metadata arguments:
1788
+ _check_type
1789
+ _path_to_item
1790
+ _spec_property_naming
1791
+ _configuration
1792
+ _visited_composed_classes
1793
+
1794
+ Returns
1795
+ composed_instances (list)
1796
+ """
1797
+ composed_instances = []
1798
+ for allof_class in self._composed_schemas['allOf']:
1799
+
1800
+ try:
1801
+ if constant_args.get('_spec_property_naming'):
1802
+ allof_instance = allof_class._from_openapi_data(**model_args, **constant_args)
1803
+ else:
1804
+ allof_instance = allof_class(**model_args, **constant_args)
1805
+ composed_instances.append(allof_instance)
1806
+ except Exception as ex:
1807
+ raise ApiValueError(
1808
+ "Invalid inputs given to generate an instance of '%s'. The "
1809
+ "input data was invalid for the allOf schema '%s' in the composed "
1810
+ "schema '%s'. Error=%s" % (
1811
+ allof_class.__name__,
1812
+ allof_class.__name__,
1813
+ self.__class__.__name__,
1814
+ str(ex)
1815
+ )
1816
+ ) from ex
1817
+ return composed_instances
1818
+
1819
+
1820
+ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
1821
+ """
1822
+ Find the oneOf schema that matches the input data (e.g. payload).
1823
+ If exactly one schema matches the input data, an instance of that schema
1824
+ is returned.
1825
+ If zero or more than one schema match the input data, an exception is raised.
1826
+ In OAS 3.x, the payload MUST, by validation, match exactly one of the
1827
+ schemas described by oneOf.
1828
+
1829
+ Args:
1830
+ cls: the class we are handling
1831
+ model_kwargs (dict): var_name to var_value
1832
+ The input data, e.g. the payload that must match a oneOf schema
1833
+ in the OpenAPI document.
1834
+ constant_kwargs (dict): var_name to var_value
1835
+ args that every model requires, including configuration, server
1836
+ and path to item.
1837
+
1838
+ Kwargs:
1839
+ model_arg: (int, float, bool, str, date, datetime, ModelSimple, None):
1840
+ the value to assign to a primitive class or ModelSimple class
1841
+ Notes:
1842
+ - this is only passed in when oneOf includes types which are not object
1843
+ - None is used to suppress handling of model_arg, nullable models are handled in __new__
1844
+
1845
+ Returns
1846
+ oneof_instance (instance)
1847
+ """
1848
+ if len(cls._composed_schemas['oneOf']) == 0:
1849
+ return None
1850
+
1851
+ oneof_instances = []
1852
+ # Iterate over each oneOf schema and determine if the input data
1853
+ # matches the oneOf schemas.
1854
+ for oneof_class in cls._composed_schemas['oneOf']:
1855
+ # The composed oneOf schema allows the 'null' type and the input data
1856
+ # is the null value. This is a OAS >= 3.1 feature.
1857
+ if oneof_class is none_type:
1858
+ # skip none_types because we are deserializing dict data.
1859
+ # none_type deserialization is handled in the __new__ method
1860
+ continue
1861
+
1862
+ single_value_input = allows_single_value_input(oneof_class)
1863
+
1864
+ try:
1865
+ if not single_value_input:
1866
+ if constant_kwargs.get('_spec_property_naming'):
1867
+ oneof_instance = oneof_class._from_openapi_data(
1868
+ **model_kwargs, **constant_kwargs)
1869
+ else:
1870
+ oneof_instance = oneof_class(**model_kwargs, **constant_kwargs)
1871
+ else:
1872
+ if issubclass(oneof_class, ModelSimple):
1873
+ if constant_kwargs.get('_spec_property_naming'):
1874
+ oneof_instance = oneof_class._from_openapi_data(
1875
+ model_arg, **constant_kwargs)
1876
+ else:
1877
+ oneof_instance = oneof_class(model_arg, **constant_kwargs)
1878
+ elif oneof_class in PRIMITIVE_TYPES:
1879
+ oneof_instance = validate_and_convert_types(
1880
+ model_arg,
1881
+ (oneof_class,),
1882
+ constant_kwargs['_path_to_item'],
1883
+ constant_kwargs['_spec_property_naming'],
1884
+ constant_kwargs['_check_type'],
1885
+ configuration=constant_kwargs['_configuration']
1886
+ )
1887
+ oneof_instances.append(oneof_instance)
1888
+ except Exception:
1889
+ pass
1890
+ if len(oneof_instances) == 0:
1891
+ raise ApiValueError(
1892
+ "Invalid inputs given to generate an instance of %s. None "
1893
+ "of the oneOf schemas matched the input data." %
1894
+ cls.__name__
1895
+ )
1896
+ elif len(oneof_instances) > 1:
1897
+ raise ApiValueError(
1898
+ "Invalid inputs given to generate an instance of %s. Multiple "
1899
+ "oneOf schemas matched the inputs, but a max of one is allowed." %
1900
+ cls.__name__
1901
+ )
1902
+ return oneof_instances[0]
1903
+
1904
+
1905
+ def get_anyof_instances(self, model_args, constant_args):
1906
+ """
1907
+ Args:
1908
+ self: the class we are handling
1909
+ model_args (dict): var_name to var_value
1910
+ The input data, e.g. the payload that must match at least one
1911
+ anyOf child schema in the OpenAPI document.
1912
+ constant_args (dict): var_name to var_value
1913
+ args that every model requires, including configuration, server
1914
+ and path to item.
1915
+
1916
+ Returns
1917
+ anyof_instances (list)
1918
+ """
1919
+ anyof_instances = []
1920
+ if len(self._composed_schemas['anyOf']) == 0:
1921
+ return anyof_instances
1922
+
1923
+ for anyof_class in self._composed_schemas['anyOf']:
1924
+ # The composed oneOf schema allows the 'null' type and the input data
1925
+ # is the null value. This is a OAS >= 3.1 feature.
1926
+ if anyof_class is none_type:
1927
+ # skip none_types because we are deserializing dict data.
1928
+ # none_type deserialization is handled in the __new__ method
1929
+ continue
1930
+
1931
+ try:
1932
+ if constant_args.get('_spec_property_naming'):
1933
+ anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args)
1934
+ else:
1935
+ anyof_instance = anyof_class(**model_args, **constant_args)
1936
+ anyof_instances.append(anyof_instance)
1937
+ except Exception:
1938
+ pass
1939
+ if len(anyof_instances) == 0:
1940
+ raise ApiValueError(
1941
+ "Invalid inputs given to generate an instance of %s. None of the "
1942
+ "anyOf schemas matched the inputs." %
1943
+ self.__class__.__name__
1944
+ )
1945
+ return anyof_instances
1946
+
1947
+
1948
+ def get_discarded_args(self, composed_instances, model_args):
1949
+ """
1950
+ Gathers the args that were discarded by configuration.discard_unknown_keys
1951
+ """
1952
+ model_arg_keys = model_args.keys()
1953
+ discarded_args = set()
1954
+ # arguments passed to self were already converted to python names
1955
+ # before __init__ was called
1956
+ for instance in composed_instances:
1957
+ if instance.__class__ in self._composed_schemas['allOf']:
1958
+ try:
1959
+ keys = instance.to_dict().keys()
1960
+ discarded_keys = model_args - keys
1961
+ discarded_args.update(discarded_keys)
1962
+ except Exception:
1963
+ # allOf integer schema will throw exception
1964
+ pass
1965
+ else:
1966
+ try:
1967
+ all_keys = set(model_to_dict(instance, serialize=False).keys())
1968
+ js_keys = model_to_dict(instance, serialize=True).keys()
1969
+ all_keys.update(js_keys)
1970
+ discarded_keys = model_arg_keys - all_keys
1971
+ discarded_args.update(discarded_keys)
1972
+ except Exception:
1973
+ # allOf integer schema will throw exception
1974
+ pass
1975
+ return discarded_args
1976
+
1977
+
1978
+ def validate_get_composed_info(constant_args, model_args, self):
1979
+ """
1980
+ For composed schemas, generate schema instances for
1981
+ all schemas in the oneOf/anyOf/allOf definition. If additional
1982
+ properties are allowed, also assign those properties on
1983
+ all matched schemas that contain additionalProperties.
1984
+ Openapi schemas are python classes.
1985
+
1986
+ Exceptions are raised if:
1987
+ - 0 or > 1 oneOf schema matches the model_args input data
1988
+ - no anyOf schema matches the model_args input data
1989
+ - any of the allOf schemas do not match the model_args input data
1990
+
1991
+ Args:
1992
+ constant_args (dict): these are the args that every model requires
1993
+ model_args (dict): these are the required and optional spec args that
1994
+ were passed in to make this model
1995
+ self (class): the class that we are instantiating
1996
+ This class contains self._composed_schemas
1997
+
1998
+ Returns:
1999
+ composed_info (list): length three
2000
+ composed_instances (list): the composed instances which are not
2001
+ self
2002
+ var_name_to_model_instances (dict): a dict going from var_name
2003
+ to the model_instance which holds that var_name
2004
+ the model_instance may be self or an instance of one of the
2005
+ classes in self.composed_instances()
2006
+ additional_properties_model_instances (list): a list of the
2007
+ model instances which have the property
2008
+ additional_properties_type. This list can include self
2009
+ """
2010
+ # create composed_instances
2011
+ composed_instances = []
2012
+ allof_instances = get_allof_instances(self, model_args, constant_args)
2013
+ composed_instances.extend(allof_instances)
2014
+ oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args)
2015
+ if oneof_instance is not None:
2016
+ composed_instances.append(oneof_instance)
2017
+ anyof_instances = get_anyof_instances(self, model_args, constant_args)
2018
+ composed_instances.extend(anyof_instances)
2019
+ """
2020
+ set additional_properties_model_instances
2021
+ additional properties must be evaluated at the schema level
2022
+ so self's additional properties are most important
2023
+ If self is a composed schema with:
2024
+ - no properties defined in self
2025
+ - additionalProperties: False
2026
+ Then for object payloads every property is an additional property
2027
+ and they are not allowed, so only empty dict is allowed
2028
+
2029
+ Properties must be set on all matching schemas
2030
+ so when a property is assigned toa composed instance, it must be set on all
2031
+ composed instances regardless of additionalProperties presence
2032
+ keeping it to prevent breaking changes in v5.0.1
2033
+ TODO remove cls._additional_properties_model_instances in 6.0.0
2034
+ """
2035
+ additional_properties_model_instances = []
2036
+ if self.additional_properties_type is not None:
2037
+ additional_properties_model_instances = [self]
2038
+
2039
+ """
2040
+ no need to set properties on self in here, they will be set in __init__
2041
+ By here all composed schema oneOf/anyOf/allOf instances have their properties set using
2042
+ model_args
2043
+ """
2044
+ discarded_args = get_discarded_args(self, composed_instances, model_args)
2045
+
2046
+ # map variable names to composed_instances
2047
+ var_name_to_model_instances = {}
2048
+ for prop_name in model_args:
2049
+ if prop_name not in discarded_args:
2050
+ var_name_to_model_instances[prop_name] = [self] + composed_instances
2051
+
2052
+ return [
2053
+ composed_instances,
2054
+ var_name_to_model_instances,
2055
+ additional_properties_model_instances,
2056
+ discarded_args
2057
+ ]