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