bdpan-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. bdpan_cli/__init__.py +15 -0
  2. bdpan_cli/_vendor/__init__.py +9 -0
  3. bdpan_cli/_vendor/openapi_client/__init__.py +27 -0
  4. bdpan_cli/_vendor/openapi_client/api/__init__.py +6 -0
  5. bdpan_cli/_vendor/openapi_client/api/auth_api.py +649 -0
  6. bdpan_cli/_vendor/openapi_client/api/fileinfo_api.py +737 -0
  7. bdpan_cli/_vendor/openapi_client/api/filemanager_api.py +669 -0
  8. bdpan_cli/_vendor/openapi_client/api/fileupload_api.py +599 -0
  9. bdpan_cli/_vendor/openapi_client/api/multimediafile_api.py +391 -0
  10. bdpan_cli/_vendor/openapi_client/api/userinfo_api.py +315 -0
  11. bdpan_cli/_vendor/openapi_client/api_client.py +864 -0
  12. bdpan_cli/_vendor/openapi_client/configuration.py +454 -0
  13. bdpan_cli/_vendor/openapi_client/exceptions.py +197 -0
  14. bdpan_cli/_vendor/openapi_client/model/__init__.py +5 -0
  15. bdpan_cli/_vendor/openapi_client/model/oauth_token_authorization_code_response.py +276 -0
  16. bdpan_cli/_vendor/openapi_client/model/oauth_token_device_code_response.py +276 -0
  17. bdpan_cli/_vendor/openapi_client/model/oauth_token_device_token_response.py +276 -0
  18. bdpan_cli/_vendor/openapi_client/model/oauth_token_refresh_token_response.py +276 -0
  19. bdpan_cli/_vendor/openapi_client/model/quotaresponse.py +276 -0
  20. bdpan_cli/_vendor/openapi_client/model/uinforesponse.py +284 -0
  21. bdpan_cli/_vendor/openapi_client/model_utils.py +2039 -0
  22. bdpan_cli/_vendor/openapi_client/rest.py +385 -0
  23. bdpan_cli/_version.py +3 -0
  24. bdpan_cli/account.py +78 -0
  25. bdpan_cli/apply_scrape_rename.py +99 -0
  26. bdpan_cli/auth.py +218 -0
  27. bdpan_cli/cli.py +1428 -0
  28. bdpan_cli/config.py +26 -0
  29. bdpan_cli/dedup.py +310 -0
  30. bdpan_cli/downloader.py +178 -0
  31. bdpan_cli/file_manager.py +389 -0
  32. bdpan_cli/foldering.py +181 -0
  33. bdpan_cli/logger.py +101 -0
  34. bdpan_cli/mcp_server.py +547 -0
  35. bdpan_cli/media_info.py +251 -0
  36. bdpan_cli/ops.py +173 -0
  37. bdpan_cli/organize.py +108 -0
  38. bdpan_cli/preview_scrape.py +182 -0
  39. bdpan_cli/scraper.py +505 -0
  40. bdpan_cli/uploader.py +391 -0
  41. bdpan_cli-0.1.0.dist-info/METADATA +167 -0
  42. bdpan_cli-0.1.0.dist-info/RECORD +44 -0
  43. bdpan_cli-0.1.0.dist-info/WHEEL +4 -0
  44. bdpan_cli-0.1.0.dist-info/entry_points.txt +5 -0
@@ -0,0 +1,2039 @@
1
+ # !/usr/bin/env python3
2
+ """
3
+ xpan
4
+
5
+ xpanapi # noqa: E501
6
+
7
+ The version of the OpenAPI document: 0.1
8
+ Generated by: https://openapi-generator.tech
9
+ """
10
+
11
+
12
+ from datetime import date, datetime # noqa: F401
13
+ from copy import deepcopy
14
+ import inspect
15
+ import io
16
+ import os
17
+ import pprint
18
+ import re
19
+ import tempfile
20
+
21
+ from dateutil.parser import parse
22
+
23
+ from bdpan_cli._vendor.openapi_client.exceptions import (
24
+ ApiKeyError,
25
+ ApiAttributeError,
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
+
37
+ @wraps(fn)
38
+ def wrapped_init(_self, *args, **kwargs):
39
+ """
40
+ An attribute named `self` received from the api will conflicts with the reserved `self`
41
+ parameter of a class method. During generation, `self` attributes are mapped
42
+ to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts.
43
+ """
44
+ spec_property_naming = kwargs.get('_spec_property_naming', False)
45
+ if spec_property_naming:
46
+ kwargs = change_keys_js_to_python(
47
+ kwargs, _self if isinstance(_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 self.new_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
+ def __new__(cls, *args, **kwargs):
215
+ # this function uses the discriminator to
216
+ # pick a new schema/class to instantiate because a discriminator
217
+ # propertyName value was passed in
218
+
219
+ if len(args) == 1:
220
+ arg = args[0]
221
+ if arg is None and is_type_nullable(cls):
222
+ # The input data is the 'null' value and the type is nullable.
223
+ return None
224
+
225
+ if issubclass(cls, ModelComposed) and allows_single_value_input(cls):
226
+ model_kwargs = {}
227
+ oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg)
228
+ return oneof_instance
229
+
230
+ visited_composed_classes = kwargs.get('_visited_composed_classes', ())
231
+ if (
232
+ cls.discriminator is None or
233
+ cls in visited_composed_classes
234
+ ):
235
+ # Use case 1: this openapi schema (cls) does not have a discriminator
236
+ # Use case 2: we have already visited this class before and are sure that we
237
+ # want to instantiate it this time. We have visited this class deserializing
238
+ # a payload with a discriminator. During that process we traveled through
239
+ # this class but did not make an instance of it. Now we are making an
240
+ # instance of a composed class which contains cls in it, so this time make an instance of cls.
241
+ #
242
+ # Here's an example of use case 2: If Animal has a discriminator
243
+ # petType and we pass in "Dog", and the class Dog
244
+ # allOf includes Animal, we move through Animal
245
+ # once using the discriminator, and pick Dog.
246
+ # Then in the composed schema dog Dog, we will make an instance of the
247
+ # Animal class (because Dal has allOf: Animal) but this time we won't travel
248
+ # through Animal's discriminator because we passed in
249
+ # _visited_composed_classes = (Animal,)
250
+
251
+ return super(OpenApiModel, cls).__new__(cls)
252
+
253
+ # Get the name and value of the discriminator property.
254
+ # The discriminator name is obtained from the discriminator meta-data
255
+ # and the discriminator value is obtained from the input data.
256
+ discr_propertyname_py = list(cls.discriminator.keys())[0]
257
+ discr_propertyname_js = cls.attribute_map[discr_propertyname_py]
258
+ if discr_propertyname_js in kwargs:
259
+ discr_value = kwargs[discr_propertyname_js]
260
+ elif discr_propertyname_py in kwargs:
261
+ discr_value = kwargs[discr_propertyname_py]
262
+ else:
263
+ # The input data does not contain the discriminator property.
264
+ path_to_item = kwargs.get('_path_to_item', ())
265
+ raise ApiValueError(
266
+ "Cannot deserialize input data due to missing discriminator. "
267
+ "The discriminator property '%s' is missing at path: %s" %
268
+ (discr_propertyname_js, path_to_item)
269
+ )
270
+
271
+ # Implementation note: the last argument to get_discriminator_class
272
+ # is a list of visited classes. get_discriminator_class may recursively
273
+ # call itself and update the list of visited classes, and the initial
274
+ # value must be an empty list. Hence not using 'visited_composed_classes'
275
+ new_cls = get_discriminator_class(
276
+ cls, discr_propertyname_py, discr_value, [])
277
+ if new_cls is None:
278
+ path_to_item = kwargs.get('_path_to_item', ())
279
+ disc_prop_value = kwargs.get(
280
+ discr_propertyname_js, kwargs.get(discr_propertyname_py))
281
+ raise ApiValueError(
282
+ "Cannot deserialize input data due to invalid discriminator "
283
+ "value. The OpenAPI document has no mapping for discriminator "
284
+ "property '%s'='%s' at path: %s" %
285
+ (discr_propertyname_js, disc_prop_value, path_to_item)
286
+ )
287
+
288
+ if new_cls in visited_composed_classes:
289
+ # if we are making an instance of a composed schema Descendent
290
+ # which allOf includes Ancestor, then Ancestor contains
291
+ # a discriminator that includes Descendent.
292
+ # So if we make an instance of Descendent, we have to make an
293
+ # instance of Ancestor to hold the allOf properties.
294
+ # This code detects that use case and makes the instance of Ancestor
295
+ # For example:
296
+ # When making an instance of Dog, _visited_composed_classes = (Dog,)
297
+ # then we make an instance of Animal to include in dog._composed_instances
298
+ # so when we are here, cls is Animal
299
+ # cls.discriminator != None
300
+ # cls not in _visited_composed_classes
301
+ # new_cls = Dog
302
+ # but we know we know that we already have Dog
303
+ # because it is in visited_composed_classes
304
+ # so make Animal here
305
+ return super(OpenApiModel, cls).__new__(cls)
306
+
307
+ # Build a list containing all oneOf and anyOf descendants.
308
+ oneof_anyof_classes = None
309
+ if cls._composed_schemas is not None:
310
+ oneof_anyof_classes = (
311
+ cls._composed_schemas.get('oneOf', ()) +
312
+ cls._composed_schemas.get('anyOf', ()))
313
+ oneof_anyof_child = new_cls in oneof_anyof_classes
314
+ kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,)
315
+
316
+ if cls._composed_schemas.get('allOf') and oneof_anyof_child:
317
+ # Validate that we can make self because when we make the
318
+ # new_cls it will not include the allOf validations in self
319
+ self_inst = super(OpenApiModel, cls).__new__(cls)
320
+ self_inst.__init__(*args, **kwargs)
321
+
322
+ if kwargs.get("_spec_property_naming", False):
323
+ # when true, implies new is from deserialization
324
+ new_inst = new_cls._new_from_openapi_data(*args, **kwargs)
325
+ else:
326
+ new_inst = new_cls.__new__(new_cls, *args, **kwargs)
327
+ new_inst.__init__(*args, **kwargs)
328
+
329
+ return new_inst
330
+
331
+ @classmethod
332
+ @convert_js_args_to_python_args
333
+ def _new_from_openapi_data(cls, *args, **kwargs):
334
+ # this function uses the discriminator to
335
+ # pick a new schema/class to instantiate because a discriminator
336
+ # propertyName value was passed in
337
+
338
+ if len(args) == 1:
339
+ arg = args[0]
340
+ if arg is None and is_type_nullable(cls):
341
+ # The input data is the 'null' value and the type is nullable.
342
+ return None
343
+
344
+ if issubclass(cls, ModelComposed) and allows_single_value_input(cls):
345
+ model_kwargs = {}
346
+ oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg)
347
+ return oneof_instance
348
+
349
+ visited_composed_classes = kwargs.get('_visited_composed_classes', ())
350
+ if (
351
+ cls.discriminator is None or
352
+ cls in visited_composed_classes
353
+ ):
354
+ # Use case 1: this openapi schema (cls) does not have a discriminator
355
+ # Use case 2: we have already visited this class before and are sure that we
356
+ # want to instantiate it this time. We have visited this class deserializing
357
+ # a payload with a discriminator. During that process we traveled through
358
+ # this class but did not make an instance of it. Now we are making an
359
+ # instance of a composed class which contains cls in it, so this time make an instance of cls.
360
+ #
361
+ # Here's an example of use case 2: If Animal has a discriminator
362
+ # petType and we pass in "Dog", and the class Dog
363
+ # allOf includes Animal, we move through Animal
364
+ # once using the discriminator, and pick Dog.
365
+ # Then in the composed schema dog Dog, we will make an instance of the
366
+ # Animal class (because Dal has allOf: Animal) but this time we won't travel
367
+ # through Animal's discriminator because we passed in
368
+ # _visited_composed_classes = (Animal,)
369
+
370
+ return cls._from_openapi_data(*args, **kwargs)
371
+
372
+ # Get the name and value of the discriminator property.
373
+ # The discriminator name is obtained from the discriminator meta-data
374
+ # and the discriminator value is obtained from the input data.
375
+ discr_propertyname_py = list(cls.discriminator.keys())[0]
376
+ discr_propertyname_js = cls.attribute_map[discr_propertyname_py]
377
+ if discr_propertyname_js in kwargs:
378
+ discr_value = kwargs[discr_propertyname_js]
379
+ elif discr_propertyname_py in kwargs:
380
+ discr_value = kwargs[discr_propertyname_py]
381
+ else:
382
+ # The input data does not contain the discriminator property.
383
+ path_to_item = kwargs.get('_path_to_item', ())
384
+ raise ApiValueError(
385
+ "Cannot deserialize input data due to missing discriminator. "
386
+ "The discriminator property '%s' is missing at path: %s" %
387
+ (discr_propertyname_js, path_to_item)
388
+ )
389
+
390
+ # Implementation note: the last argument to get_discriminator_class
391
+ # is a list of visited classes. get_discriminator_class may recursively
392
+ # call itself and update the list of visited classes, and the initial
393
+ # value must be an empty list. Hence not using 'visited_composed_classes'
394
+ new_cls = get_discriminator_class(
395
+ cls, discr_propertyname_py, discr_value, [])
396
+ if new_cls is None:
397
+ path_to_item = kwargs.get('_path_to_item', ())
398
+ disc_prop_value = kwargs.get(
399
+ discr_propertyname_js, kwargs.get(discr_propertyname_py))
400
+ raise ApiValueError(
401
+ "Cannot deserialize input data due to invalid discriminator "
402
+ "value. The OpenAPI document has no mapping for discriminator "
403
+ "property '%s'='%s' at path: %s" %
404
+ (discr_propertyname_js, disc_prop_value, path_to_item)
405
+ )
406
+
407
+ if new_cls in visited_composed_classes:
408
+ # if we are making an instance of a composed schema Descendent
409
+ # which allOf includes Ancestor, then Ancestor contains
410
+ # a discriminator that includes Descendent.
411
+ # So if we make an instance of Descendent, we have to make an
412
+ # instance of Ancestor to hold the allOf properties.
413
+ # This code detects that use case and makes the instance of Ancestor
414
+ # For example:
415
+ # When making an instance of Dog, _visited_composed_classes = (Dog,)
416
+ # then we make an instance of Animal to include in dog._composed_instances
417
+ # so when we are here, cls is Animal
418
+ # cls.discriminator != None
419
+ # cls not in _visited_composed_classes
420
+ # new_cls = Dog
421
+ # but we know we know that we already have Dog
422
+ # because it is in visited_composed_classes
423
+ # so make Animal here
424
+ return cls._from_openapi_data(*args, **kwargs)
425
+
426
+ # Build a list containing all oneOf and anyOf descendants.
427
+ oneof_anyof_classes = None
428
+ if cls._composed_schemas is not None:
429
+ oneof_anyof_classes = (
430
+ cls._composed_schemas.get('oneOf', ()) +
431
+ cls._composed_schemas.get('anyOf', ()))
432
+ oneof_anyof_child = new_cls in oneof_anyof_classes
433
+ kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,)
434
+
435
+ if cls._composed_schemas.get('allOf') and oneof_anyof_child:
436
+ # Validate that we can make self because when we make the
437
+ # new_cls it will not include the allOf validations in self
438
+ self_inst = cls._from_openapi_data(*args, **kwargs)
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
+ # A float may be serialized as an integer, e.g. '3' is a valid serialized float.
741
+ (int, float),
742
+ (list, ModelComposed),
743
+ (dict, ModelComposed),
744
+ (str, ModelComposed),
745
+ (int, ModelComposed),
746
+ (float, ModelComposed),
747
+ (list, ModelComposed),
748
+ (list, ModelNormal),
749
+ (dict, ModelNormal),
750
+ (str, ModelSimple),
751
+ (int, ModelSimple),
752
+ (float, ModelSimple),
753
+ (list, ModelSimple),
754
+ )
755
+
756
+ COERCIBLE_TYPE_PAIRS = {
757
+ False: ( # client instantiation of a model with client data
758
+ # (dict, ModelComposed),
759
+ # (list, ModelComposed),
760
+ # (dict, ModelNormal),
761
+ # (list, ModelNormal),
762
+ # (str, ModelSimple),
763
+ # (int, ModelSimple),
764
+ # (float, ModelSimple),
765
+ # (list, ModelSimple),
766
+ # (str, int),
767
+ # (str, float),
768
+ # (str, datetime),
769
+ # (str, date),
770
+ # (int, str),
771
+ # (float, str),
772
+ ),
773
+ True: ( # server -> client data
774
+ (dict, ModelComposed),
775
+ (list, ModelComposed),
776
+ (dict, ModelNormal),
777
+ (list, ModelNormal),
778
+ (str, ModelSimple),
779
+ (int, ModelSimple),
780
+ (float, ModelSimple),
781
+ (list, ModelSimple),
782
+ # (str, int),
783
+ # (str, float),
784
+ (str, datetime),
785
+ (str, date),
786
+ # (int, str),
787
+ # (float, str),
788
+ (str, file_type)
789
+ ),
790
+ }
791
+
792
+
793
+ def get_simple_class(input_value):
794
+ """Returns an input_value's simple class that we will use for type checking
795
+ Python2:
796
+ float and int will return int, where int is the python3 int backport
797
+ str and unicode will return str, where str is the python3 str backport
798
+ Note: float and int ARE both instances of int backport
799
+ Note: str_py2 and unicode_py2 are NOT both instances of str backport
800
+
801
+ Args:
802
+ input_value (class/class_instance): the item for which we will return
803
+ the simple class
804
+ """
805
+ if isinstance(input_value, type):
806
+ # input_value is a class
807
+ return input_value
808
+ elif isinstance(input_value, tuple):
809
+ return tuple
810
+ elif isinstance(input_value, list):
811
+ return list
812
+ elif isinstance(input_value, dict):
813
+ return dict
814
+ elif isinstance(input_value, none_type):
815
+ return none_type
816
+ elif isinstance(input_value, file_type):
817
+ return file_type
818
+ elif isinstance(input_value, bool):
819
+ # this must be higher than the int check because
820
+ # isinstance(True, int) == True
821
+ return bool
822
+ elif isinstance(input_value, int):
823
+ return int
824
+ elif isinstance(input_value, datetime):
825
+ # this must be higher than the date check because
826
+ # isinstance(datetime_instance, date) == True
827
+ return datetime
828
+ elif isinstance(input_value, date):
829
+ return date
830
+ elif isinstance(input_value, str):
831
+ return str
832
+ return type(input_value)
833
+
834
+
835
+ def check_allowed_values(allowed_values, input_variable_path, input_values):
836
+ """Raises an exception if the input_values are not allowed
837
+
838
+ Args:
839
+ allowed_values (dict): the allowed_values dict
840
+ input_variable_path (tuple): the path to the input variable
841
+ input_values (list/str/int/float/date/datetime): the values that we
842
+ are checking to see if they are in allowed_values
843
+ """
844
+ these_allowed_values = list(allowed_values[input_variable_path].values())
845
+ if (isinstance(input_values, list)
846
+ and not set(input_values).issubset(
847
+ set(these_allowed_values))):
848
+ invalid_values = ", ".join(
849
+ map(str, set(input_values) - set(these_allowed_values))),
850
+ raise ApiValueError(
851
+ "Invalid values for `%s` [%s], must be a subset of [%s]" %
852
+ (
853
+ input_variable_path[0],
854
+ invalid_values,
855
+ ", ".join(map(str, these_allowed_values))
856
+ )
857
+ )
858
+ elif (isinstance(input_values, dict)
859
+ and not set(
860
+ input_values.keys()).issubset(set(these_allowed_values))):
861
+ invalid_values = ", ".join(
862
+ map(str, set(input_values.keys()) - set(these_allowed_values)))
863
+ raise ApiValueError(
864
+ "Invalid keys in `%s` [%s], must be a subset of [%s]" %
865
+ (
866
+ input_variable_path[0],
867
+ invalid_values,
868
+ ", ".join(map(str, these_allowed_values))
869
+ )
870
+ )
871
+ elif (not isinstance(input_values, (list, dict))
872
+ and input_values not in these_allowed_values):
873
+ raise ApiValueError(
874
+ "Invalid value for `%s` (%s), must be one of %s" %
875
+ (
876
+ input_variable_path[0],
877
+ input_values,
878
+ these_allowed_values
879
+ )
880
+ )
881
+
882
+
883
+ def is_json_validation_enabled(schema_keyword, configuration=None):
884
+ """Returns true if JSON schema validation is enabled for the specified
885
+ validation keyword. This can be used to skip JSON schema structural validation
886
+ as requested in the configuration.
887
+
888
+ Args:
889
+ schema_keyword (string): the name of a JSON schema validation keyword.
890
+ configuration (Configuration): the configuration class.
891
+ """
892
+
893
+ return (configuration is None or
894
+ not hasattr(configuration, '_disabled_client_side_validations') or
895
+ schema_keyword not in configuration._disabled_client_side_validations)
896
+
897
+
898
+ def check_validations(
899
+ validations, input_variable_path, input_values,
900
+ configuration=None):
901
+ """Raises an exception if the input_values are invalid
902
+
903
+ Args:
904
+ validations (dict): the validation dictionary.
905
+ input_variable_path (tuple): the path to the input variable.
906
+ input_values (list/str/int/float/date/datetime): the values that we
907
+ are checking.
908
+ configuration (Configuration): the configuration class.
909
+ """
910
+
911
+ if input_values is None:
912
+ return
913
+
914
+ current_validations = validations[input_variable_path]
915
+ if (is_json_validation_enabled('multipleOf', configuration) and
916
+ 'multiple_of' in current_validations and
917
+ isinstance(input_values, (int, float)) and
918
+ not (float(input_values) / current_validations['multiple_of']).is_integer()):
919
+ # Note 'multipleOf' will be as good as the floating point arithmetic.
920
+ raise ApiValueError(
921
+ "Invalid value for `%s`, value must be a multiple of "
922
+ "`%s`" % (
923
+ input_variable_path[0],
924
+ current_validations['multiple_of']
925
+ )
926
+ )
927
+
928
+ if (is_json_validation_enabled('maxLength', configuration) and
929
+ 'max_length' in current_validations and
930
+ len(input_values) > current_validations['max_length']):
931
+ raise ApiValueError(
932
+ "Invalid value for `%s`, length must be less than or equal to "
933
+ "`%s`" % (
934
+ input_variable_path[0],
935
+ current_validations['max_length']
936
+ )
937
+ )
938
+
939
+ if (is_json_validation_enabled('minLength', configuration) and
940
+ 'min_length' in current_validations and
941
+ len(input_values) < current_validations['min_length']):
942
+ raise ApiValueError(
943
+ "Invalid value for `%s`, length must be greater than or equal to "
944
+ "`%s`" % (
945
+ input_variable_path[0],
946
+ current_validations['min_length']
947
+ )
948
+ )
949
+
950
+ if (is_json_validation_enabled('maxItems', configuration) and
951
+ 'max_items' in current_validations and
952
+ len(input_values) > current_validations['max_items']):
953
+ raise ApiValueError(
954
+ "Invalid value for `%s`, number of items must be less than or "
955
+ "equal to `%s`" % (
956
+ input_variable_path[0],
957
+ current_validations['max_items']
958
+ )
959
+ )
960
+
961
+ if (is_json_validation_enabled('minItems', configuration) and
962
+ 'min_items' in current_validations and
963
+ len(input_values) < current_validations['min_items']):
964
+ raise ValueError(
965
+ "Invalid value for `%s`, number of items must be greater than or "
966
+ "equal to `%s`" % (
967
+ input_variable_path[0],
968
+ current_validations['min_items']
969
+ )
970
+ )
971
+
972
+ items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum',
973
+ 'inclusive_minimum')
974
+ if (any(item in current_validations for item in items)):
975
+ if isinstance(input_values, list):
976
+ max_val = max(input_values)
977
+ min_val = min(input_values)
978
+ elif isinstance(input_values, dict):
979
+ max_val = max(input_values.values())
980
+ min_val = min(input_values.values())
981
+ else:
982
+ max_val = input_values
983
+ min_val = input_values
984
+
985
+ if (is_json_validation_enabled('exclusiveMaximum', configuration) and
986
+ 'exclusive_maximum' in current_validations and
987
+ max_val >= current_validations['exclusive_maximum']):
988
+ raise ApiValueError(
989
+ "Invalid value for `%s`, must be a value less than `%s`" % (
990
+ input_variable_path[0],
991
+ current_validations['exclusive_maximum']
992
+ )
993
+ )
994
+
995
+ if (is_json_validation_enabled('maximum', configuration) and
996
+ 'inclusive_maximum' in current_validations and
997
+ max_val > current_validations['inclusive_maximum']):
998
+ raise ApiValueError(
999
+ "Invalid value for `%s`, must be a value less than or equal to "
1000
+ "`%s`" % (
1001
+ input_variable_path[0],
1002
+ current_validations['inclusive_maximum']
1003
+ )
1004
+ )
1005
+
1006
+ if (is_json_validation_enabled('exclusiveMinimum', configuration) and
1007
+ 'exclusive_minimum' in current_validations and
1008
+ min_val <= current_validations['exclusive_minimum']):
1009
+ raise ApiValueError(
1010
+ "Invalid value for `%s`, must be a value greater than `%s`" %
1011
+ (
1012
+ input_variable_path[0],
1013
+ current_validations['exclusive_maximum']
1014
+ )
1015
+ )
1016
+
1017
+ if (is_json_validation_enabled('minimum', configuration) and
1018
+ 'inclusive_minimum' in current_validations and
1019
+ min_val < current_validations['inclusive_minimum']):
1020
+ raise ApiValueError(
1021
+ "Invalid value for `%s`, must be a value greater than or equal "
1022
+ "to `%s`" % (
1023
+ input_variable_path[0],
1024
+ current_validations['inclusive_minimum']
1025
+ )
1026
+ )
1027
+ flags = current_validations.get('regex', {}).get('flags', 0)
1028
+ if (is_json_validation_enabled('pattern', configuration) and
1029
+ 'regex' in current_validations and
1030
+ not re.search(current_validations['regex']['pattern'],
1031
+ input_values, flags=flags)):
1032
+ err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % (
1033
+ input_variable_path[0],
1034
+ current_validations['regex']['pattern']
1035
+ )
1036
+ if flags != 0:
1037
+ # Don't print the regex flags if the flags are not
1038
+ # specified in the OAS document.
1039
+ err_msg = r"%s with flags=`%s`" % (err_msg, flags)
1040
+ raise ApiValueError(err_msg)
1041
+
1042
+
1043
+ def order_response_types(required_types):
1044
+ """Returns the required types sorted in coercion order
1045
+
1046
+ Args:
1047
+ required_types (list/tuple): collection of classes or instance of
1048
+ list or dict with class information inside it.
1049
+
1050
+ Returns:
1051
+ (list): coercion order sorted collection of classes or instance
1052
+ of list or dict with class information inside it.
1053
+ """
1054
+
1055
+ def index_getter(class_or_instance):
1056
+ if isinstance(class_or_instance, list):
1057
+ return COERCION_INDEX_BY_TYPE[list]
1058
+ elif isinstance(class_or_instance, dict):
1059
+ return COERCION_INDEX_BY_TYPE[dict]
1060
+ elif (inspect.isclass(class_or_instance)
1061
+ and issubclass(class_or_instance, ModelComposed)):
1062
+ return COERCION_INDEX_BY_TYPE[ModelComposed]
1063
+ elif (inspect.isclass(class_or_instance)
1064
+ and issubclass(class_or_instance, ModelNormal)):
1065
+ return COERCION_INDEX_BY_TYPE[ModelNormal]
1066
+ elif (inspect.isclass(class_or_instance)
1067
+ and issubclass(class_or_instance, ModelSimple)):
1068
+ return COERCION_INDEX_BY_TYPE[ModelSimple]
1069
+ elif class_or_instance in COERCION_INDEX_BY_TYPE:
1070
+ return COERCION_INDEX_BY_TYPE[class_or_instance]
1071
+ raise ApiValueError("Unsupported type: %s" % class_or_instance)
1072
+
1073
+ sorted_types = sorted(
1074
+ required_types,
1075
+ key=lambda class_or_instance: index_getter(class_or_instance)
1076
+ )
1077
+ return sorted_types
1078
+
1079
+
1080
+ def remove_uncoercible(required_types_classes, current_item, spec_property_naming,
1081
+ must_convert=True):
1082
+ """Only keeps the type conversions that are possible
1083
+
1084
+ Args:
1085
+ required_types_classes (tuple): tuple of classes that are required
1086
+ these should be ordered by COERCION_INDEX_BY_TYPE
1087
+ spec_property_naming (bool): True if the variable names in the input
1088
+ data are serialized names as specified in the OpenAPI document.
1089
+ False if the variables names in the input data are python
1090
+ variable names in PEP-8 snake case.
1091
+ current_item (any): the current item (input data) to be converted
1092
+
1093
+ Keyword Args:
1094
+ must_convert (bool): if True the item to convert is of the wrong
1095
+ type and we want a big list of coercibles
1096
+ if False, we want a limited list of coercibles
1097
+
1098
+ Returns:
1099
+ (list): the remaining coercible required types, classes only
1100
+ """
1101
+ current_type_simple = get_simple_class(current_item)
1102
+
1103
+ results_classes = []
1104
+ for required_type_class in required_types_classes:
1105
+ # convert our models to OpenApiModel
1106
+ required_type_class_simplified = required_type_class
1107
+ if isinstance(required_type_class_simplified, type):
1108
+ if issubclass(required_type_class_simplified, ModelComposed):
1109
+ required_type_class_simplified = ModelComposed
1110
+ elif issubclass(required_type_class_simplified, ModelNormal):
1111
+ required_type_class_simplified = ModelNormal
1112
+ elif issubclass(required_type_class_simplified, ModelSimple):
1113
+ required_type_class_simplified = ModelSimple
1114
+
1115
+ if required_type_class_simplified == current_type_simple:
1116
+ # don't consider converting to one's own class
1117
+ continue
1118
+
1119
+ class_pair = (current_type_simple, required_type_class_simplified)
1120
+ if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]:
1121
+ results_classes.append(required_type_class)
1122
+ elif class_pair in UPCONVERSION_TYPE_PAIRS:
1123
+ results_classes.append(required_type_class)
1124
+ return results_classes
1125
+
1126
+
1127
+ def get_discriminated_classes(cls):
1128
+ """
1129
+ Returns all the classes that a discriminator converts to
1130
+ TODO: lru_cache this
1131
+ """
1132
+ possible_classes = []
1133
+ key = list(cls.discriminator.keys())[0]
1134
+ if is_type_nullable(cls):
1135
+ possible_classes.append(cls)
1136
+ for discr_cls in cls.discriminator[key].values():
1137
+ if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None:
1138
+ possible_classes.extend(get_discriminated_classes(discr_cls))
1139
+ else:
1140
+ possible_classes.append(discr_cls)
1141
+ return possible_classes
1142
+
1143
+
1144
+ def get_possible_classes(cls, from_server_context):
1145
+ # TODO: lru_cache this
1146
+ possible_classes = [cls]
1147
+ if from_server_context:
1148
+ return possible_classes
1149
+ if hasattr(cls, 'discriminator') and cls.discriminator is not None:
1150
+ possible_classes = []
1151
+ possible_classes.extend(get_discriminated_classes(cls))
1152
+ elif issubclass(cls, ModelComposed):
1153
+ possible_classes.extend(composed_model_input_classes(cls))
1154
+ return possible_classes
1155
+
1156
+
1157
+ def get_required_type_classes(required_types_mixed, spec_property_naming):
1158
+ """Converts the tuple required_types into a tuple and a dict described
1159
+ below
1160
+
1161
+ Args:
1162
+ required_types_mixed (tuple/list): will contain either classes or
1163
+ instance of list or dict
1164
+ spec_property_naming (bool): if True these values came from the
1165
+ server, and we use the data types in our endpoints.
1166
+ If False, we are client side and we need to include
1167
+ oneOf and discriminator classes inside the data types in our endpoints
1168
+
1169
+ Returns:
1170
+ (valid_classes, dict_valid_class_to_child_types_mixed):
1171
+ valid_classes (tuple): the valid classes that the current item
1172
+ should be
1173
+ dict_valid_class_to_child_types_mixed (dict):
1174
+ valid_class (class): this is the key
1175
+ child_types_mixed (list/dict/tuple): describes the valid child
1176
+ types
1177
+ """
1178
+ valid_classes = []
1179
+ child_req_types_by_current_type = {}
1180
+ for required_type in required_types_mixed:
1181
+ if isinstance(required_type, list):
1182
+ valid_classes.append(list)
1183
+ child_req_types_by_current_type[list] = required_type
1184
+ elif isinstance(required_type, tuple):
1185
+ valid_classes.append(tuple)
1186
+ child_req_types_by_current_type[tuple] = required_type
1187
+ elif isinstance(required_type, dict):
1188
+ valid_classes.append(dict)
1189
+ child_req_types_by_current_type[dict] = required_type[str]
1190
+ else:
1191
+ valid_classes.extend(get_possible_classes(required_type, spec_property_naming))
1192
+ return tuple(valid_classes), child_req_types_by_current_type
1193
+
1194
+
1195
+ def change_keys_js_to_python(input_dict, model_class):
1196
+ """
1197
+ Converts from javascript_key keys in the input_dict to python_keys in
1198
+ the output dict using the mapping in model_class.
1199
+ If the input_dict contains a key which does not declared in the model_class,
1200
+ the key is added to the output dict as is. The assumption is the model_class
1201
+ may have undeclared properties (additionalProperties attribute in the OAS
1202
+ document).
1203
+ """
1204
+
1205
+ if getattr(model_class, 'attribute_map', None) is None:
1206
+ return input_dict
1207
+ output_dict = {}
1208
+ reversed_attr_map = {value: key for key, value in
1209
+ model_class.attribute_map.items()}
1210
+ for javascript_key, value in input_dict.items():
1211
+ python_key = reversed_attr_map.get(javascript_key)
1212
+ if python_key is None:
1213
+ # if the key is unknown, it is in error or it is an
1214
+ # additionalProperties variable
1215
+ python_key = javascript_key
1216
+ output_dict[python_key] = value
1217
+ return output_dict
1218
+
1219
+
1220
+ def get_type_error(var_value, path_to_item, valid_classes, key_type=False):
1221
+ error_msg = type_error_message(
1222
+ var_name=path_to_item[-1],
1223
+ var_value=var_value,
1224
+ valid_classes=valid_classes,
1225
+ key_type=key_type
1226
+ )
1227
+ return ApiTypeError(
1228
+ error_msg,
1229
+ path_to_item=path_to_item,
1230
+ valid_classes=valid_classes,
1231
+ key_type=key_type
1232
+ )
1233
+
1234
+
1235
+ def deserialize_primitive(data, klass, path_to_item):
1236
+ """Deserializes string to primitive type.
1237
+
1238
+ :param data: str/int/float
1239
+ :param klass: str/class the class to convert to
1240
+
1241
+ :return: int, float, str, bool, date, datetime
1242
+ """
1243
+ additional_message = ""
1244
+ try:
1245
+ if klass in {datetime, date}:
1246
+ additional_message = (
1247
+ "If you need your parameter to have a fallback "
1248
+ "string value, please set its type as `type: {}` in your "
1249
+ "spec. That allows the value to be any type. "
1250
+ )
1251
+ if klass == datetime:
1252
+ if len(data) < 8:
1253
+ raise ValueError("This is not a datetime")
1254
+ # The string should be in iso8601 datetime format.
1255
+ parsed_datetime = parse(data)
1256
+ date_only = (
1257
+ parsed_datetime.hour == 0 and
1258
+ parsed_datetime.minute == 0 and
1259
+ parsed_datetime.second == 0 and
1260
+ parsed_datetime.tzinfo is None and
1261
+ 8 <= len(data) <= 10
1262
+ )
1263
+ if date_only:
1264
+ raise ValueError("This is a date, not a datetime")
1265
+ return parsed_datetime
1266
+ elif klass == date:
1267
+ if len(data) < 8:
1268
+ raise ValueError("This is not a date")
1269
+ return parse(data).date()
1270
+ else:
1271
+ converted_value = klass(data)
1272
+ if isinstance(data, str) and klass == float:
1273
+ if str(converted_value) != data:
1274
+ # '7' -> 7.0 -> '7.0' != '7'
1275
+ raise ValueError('This is not a float')
1276
+ return converted_value
1277
+ except (OverflowError, ValueError) as ex:
1278
+ # parse can raise OverflowError
1279
+ raise ApiValueError(
1280
+ "{0}Failed to parse {1} as {2}".format(
1281
+ additional_message, repr(data), klass.__name__
1282
+ ),
1283
+ path_to_item=path_to_item
1284
+ ) from ex
1285
+
1286
+
1287
+ def get_discriminator_class(model_class,
1288
+ discr_name,
1289
+ discr_value, cls_visited):
1290
+ """Returns the child class specified by the discriminator.
1291
+
1292
+ Args:
1293
+ model_class (OpenApiModel): the model class.
1294
+ discr_name (string): the name of the discriminator property.
1295
+ discr_value (any): the discriminator value.
1296
+ cls_visited (list): list of model classes that have been visited.
1297
+ Used to determine the discriminator class without
1298
+ visiting circular references indefinitely.
1299
+
1300
+ Returns:
1301
+ used_model_class (class/None): the chosen child class that will be used
1302
+ to deserialize the data, for example dog.Dog.
1303
+ If a class is not found, None is returned.
1304
+ """
1305
+
1306
+ if model_class in cls_visited:
1307
+ # The class has already been visited and no suitable class was found.
1308
+ return None
1309
+ cls_visited.append(model_class)
1310
+ used_model_class = None
1311
+ if discr_name in model_class.discriminator:
1312
+ class_name_to_discr_class = model_class.discriminator[discr_name]
1313
+ used_model_class = class_name_to_discr_class.get(discr_value)
1314
+ if used_model_class is None:
1315
+ # We didn't find a discriminated class in class_name_to_discr_class.
1316
+ # So look in the ancestor or descendant discriminators
1317
+ # The discriminator mapping may exist in a descendant (anyOf, oneOf)
1318
+ # or ancestor (allOf).
1319
+ # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat
1320
+ # hierarchy, the discriminator mappings may be defined at any level
1321
+ # in the hierarchy.
1322
+ # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig
1323
+ # if we try to make BasquePig from mammal, we need to travel through
1324
+ # the oneOf descendant discriminators to find BasquePig
1325
+ descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \
1326
+ model_class._composed_schemas.get('anyOf', ())
1327
+ ancestor_classes = model_class._composed_schemas.get('allOf', ())
1328
+ possible_classes = descendant_classes + ancestor_classes
1329
+ for cls in possible_classes:
1330
+ # Check if the schema has inherited discriminators.
1331
+ if hasattr(cls, 'discriminator') and cls.discriminator is not None:
1332
+ used_model_class = get_discriminator_class(
1333
+ cls, discr_name, discr_value, cls_visited)
1334
+ if used_model_class is not None:
1335
+ return used_model_class
1336
+ return used_model_class
1337
+
1338
+
1339
+ def deserialize_model(model_data, model_class, path_to_item, check_type,
1340
+ configuration, spec_property_naming):
1341
+ """Deserializes model_data to model instance.
1342
+
1343
+ Args:
1344
+ model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model
1345
+ model_class (OpenApiModel): the model class
1346
+ path_to_item (list): path to the model in the received data
1347
+ check_type (bool): whether to check the data tupe for the values in
1348
+ the model
1349
+ configuration (Configuration): the instance to use to convert files
1350
+ spec_property_naming (bool): True if the variable names in the input
1351
+ data are serialized names as specified in the OpenAPI document.
1352
+ False if the variables names in the input data are python
1353
+ variable names in PEP-8 snake case.
1354
+
1355
+ Returns:
1356
+ model instance
1357
+
1358
+ Raise:
1359
+ ApiTypeError
1360
+ ApiValueError
1361
+ ApiKeyError
1362
+ """
1363
+
1364
+ kw_args = dict(_check_type=check_type,
1365
+ _path_to_item=path_to_item,
1366
+ _configuration=configuration,
1367
+ _spec_property_naming=spec_property_naming)
1368
+
1369
+ if issubclass(model_class, ModelSimple):
1370
+ return model_class._new_from_openapi_data(model_data, **kw_args)
1371
+ elif isinstance(model_data, list):
1372
+ return model_class._new_from_openapi_data(*model_data, **kw_args)
1373
+ if isinstance(model_data, dict):
1374
+ kw_args.update(model_data)
1375
+ return model_class._new_from_openapi_data(**kw_args)
1376
+ elif isinstance(model_data, PRIMITIVE_TYPES):
1377
+ return model_class._new_from_openapi_data(model_data, **kw_args)
1378
+
1379
+
1380
+ def deserialize_file(response_data, configuration, content_disposition=None):
1381
+ """Deserializes body to file
1382
+
1383
+ Saves response body into a file in a temporary folder,
1384
+ using the filename from the `Content-Disposition` header if provided.
1385
+
1386
+ Args:
1387
+ param response_data (str): the file data to write
1388
+ configuration (Configuration): the instance to use to convert files
1389
+
1390
+ Keyword Args:
1391
+ content_disposition (str): the value of the Content-Disposition
1392
+ header
1393
+
1394
+ Returns:
1395
+ (file_type): the deserialized file which is open
1396
+ The user is responsible for closing and reading the file
1397
+ """
1398
+ fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path)
1399
+ os.close(fd)
1400
+ os.remove(path)
1401
+
1402
+ if content_disposition:
1403
+ filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
1404
+ content_disposition).group(1)
1405
+ path = os.path.join(os.path.dirname(path), filename)
1406
+
1407
+ with open(path, "wb") as f:
1408
+ if isinstance(response_data, str):
1409
+ # change str to bytes so we can write it
1410
+ response_data = response_data.encode('utf-8')
1411
+ f.write(response_data)
1412
+
1413
+ f = open(path, "rb")
1414
+ return f
1415
+
1416
+
1417
+ def attempt_convert_item(input_value, valid_classes, path_to_item,
1418
+ configuration, spec_property_naming, key_type=False,
1419
+ must_convert=False, check_type=True):
1420
+ """
1421
+ Args:
1422
+ input_value (any): the data to convert
1423
+ valid_classes (any): the classes that are valid
1424
+ path_to_item (list): the path to the item to convert
1425
+ configuration (Configuration): the instance to use to convert files
1426
+ spec_property_naming (bool): True if the variable names in the input
1427
+ data are serialized names as specified in the OpenAPI document.
1428
+ False if the variables names in the input data are python
1429
+ variable names in PEP-8 snake case.
1430
+ key_type (bool): if True we need to convert a key type (not supported)
1431
+ must_convert (bool): if True we must convert
1432
+ check_type (bool): if True we check the type or the returned data in
1433
+ ModelComposed/ModelNormal/ModelSimple instances
1434
+
1435
+ Returns:
1436
+ instance (any) the fixed item
1437
+
1438
+ Raises:
1439
+ ApiTypeError
1440
+ ApiValueError
1441
+ ApiKeyError
1442
+ """
1443
+ valid_classes_ordered = order_response_types(valid_classes)
1444
+ valid_classes_coercible = remove_uncoercible(
1445
+ valid_classes_ordered, input_value, spec_property_naming)
1446
+ if not valid_classes_coercible or key_type:
1447
+ # we do not handle keytype errors, json will take care
1448
+ # of this for us
1449
+ if configuration is None or not configuration.discard_unknown_keys:
1450
+ raise get_type_error(input_value, path_to_item, valid_classes,
1451
+ key_type=key_type)
1452
+ for valid_class in valid_classes_coercible:
1453
+ try:
1454
+ if issubclass(valid_class, OpenApiModel):
1455
+ return deserialize_model(input_value, valid_class,
1456
+ path_to_item, check_type,
1457
+ configuration, spec_property_naming)
1458
+ elif valid_class == file_type:
1459
+ return deserialize_file(input_value, configuration)
1460
+ return deserialize_primitive(input_value, valid_class,
1461
+ path_to_item)
1462
+ except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc:
1463
+ if must_convert:
1464
+ raise conversion_exc
1465
+ # if we have conversion errors when must_convert == False
1466
+ # we ignore the exception and move on to the next class
1467
+ continue
1468
+ # we were unable to convert, must_convert == False
1469
+ return input_value
1470
+
1471
+
1472
+ def is_type_nullable(input_type):
1473
+ """
1474
+ Returns true if None is an allowed value for the specified input_type.
1475
+
1476
+ A type is nullable if at least one of the following conditions is true:
1477
+ 1. The OAS 'nullable' attribute has been specified,
1478
+ 1. The type is the 'null' type,
1479
+ 1. The type is a anyOf/oneOf composed schema, and a child schema is
1480
+ the 'null' type.
1481
+ Args:
1482
+ input_type (type): the class of the input_value that we are
1483
+ checking
1484
+ Returns:
1485
+ bool
1486
+ """
1487
+ if input_type is none_type:
1488
+ return True
1489
+ if issubclass(input_type, OpenApiModel) and input_type._nullable:
1490
+ return True
1491
+ if issubclass(input_type, ModelComposed):
1492
+ # If oneOf/anyOf, check if the 'null' type is one of the allowed types.
1493
+ for t in input_type._composed_schemas.get('oneOf', ()):
1494
+ if is_type_nullable(t):
1495
+ return True
1496
+ for t in input_type._composed_schemas.get('anyOf', ()):
1497
+ if is_type_nullable(t):
1498
+ return True
1499
+ return False
1500
+
1501
+
1502
+ def is_valid_type(input_class_simple, valid_classes):
1503
+ """
1504
+ Args:
1505
+ input_class_simple (class): the class of the input_value that we are
1506
+ checking
1507
+ valid_classes (tuple): the valid classes that the current item
1508
+ should be
1509
+ Returns:
1510
+ bool
1511
+ """
1512
+ if issubclass(input_class_simple, OpenApiModel) and \
1513
+ valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,):
1514
+ return True
1515
+ valid_type = input_class_simple in valid_classes
1516
+ if not valid_type and (
1517
+ issubclass(input_class_simple, OpenApiModel) or
1518
+ input_class_simple is none_type):
1519
+ for valid_class in valid_classes:
1520
+ if input_class_simple is none_type and is_type_nullable(valid_class):
1521
+ # Schema is oneOf/anyOf and the 'null' type is one of the allowed types.
1522
+ return True
1523
+ if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator):
1524
+ continue
1525
+ discr_propertyname_py = list(valid_class.discriminator.keys())[0]
1526
+ discriminator_classes = (
1527
+ valid_class.discriminator[discr_propertyname_py].values()
1528
+ )
1529
+ valid_type = is_valid_type(input_class_simple, discriminator_classes)
1530
+ if valid_type:
1531
+ return True
1532
+ return valid_type
1533
+
1534
+
1535
+ def validate_and_convert_types(input_value, required_types_mixed, path_to_item,
1536
+ spec_property_naming, _check_type, configuration=None):
1537
+ """Raises a TypeError is there is a problem, otherwise returns value
1538
+
1539
+ Args:
1540
+ input_value (any): the data to validate/convert
1541
+ required_types_mixed (list/dict/tuple): A list of
1542
+ valid classes, or a list tuples of valid classes, or a dict where
1543
+ the value is a tuple of value classes
1544
+ path_to_item: (list) the path to the data being validated
1545
+ this stores a list of keys or indices to get to the data being
1546
+ validated
1547
+ spec_property_naming (bool): True if the variable names in the input
1548
+ data are serialized names as specified in the OpenAPI document.
1549
+ False if the variables names in the input data are python
1550
+ variable names in PEP-8 snake case.
1551
+ _check_type: (boolean) if true, type will be checked and conversion
1552
+ will be attempted.
1553
+ configuration: (Configuration): the configuration class to use
1554
+ when converting file_type items.
1555
+ If passed, conversion will be attempted when possible
1556
+ If not passed, no conversions will be attempted and
1557
+ exceptions will be raised
1558
+
1559
+ Returns:
1560
+ the correctly typed value
1561
+
1562
+ Raises:
1563
+ ApiTypeError
1564
+ """
1565
+ results = get_required_type_classes(required_types_mixed, spec_property_naming)
1566
+ valid_classes, child_req_types_by_current_type = results
1567
+
1568
+ input_class_simple = get_simple_class(input_value)
1569
+ valid_type = is_valid_type(input_class_simple, valid_classes)
1570
+ if not valid_type:
1571
+ if configuration:
1572
+ # if input_value is not valid_type try to convert it
1573
+ converted_instance = attempt_convert_item(
1574
+ input_value,
1575
+ valid_classes,
1576
+ path_to_item,
1577
+ configuration,
1578
+ spec_property_naming,
1579
+ key_type=False,
1580
+ must_convert=True,
1581
+ check_type=_check_type
1582
+ )
1583
+ return converted_instance
1584
+ else:
1585
+ raise get_type_error(input_value, path_to_item, valid_classes,
1586
+ key_type=False)
1587
+
1588
+ # input_value's type is in valid_classes
1589
+ if len(valid_classes) > 1 and configuration:
1590
+ # there are valid classes which are not the current class
1591
+ valid_classes_coercible = remove_uncoercible(
1592
+ valid_classes, input_value, spec_property_naming, must_convert=False)
1593
+ if valid_classes_coercible:
1594
+ converted_instance = attempt_convert_item(
1595
+ input_value,
1596
+ valid_classes_coercible,
1597
+ path_to_item,
1598
+ configuration,
1599
+ spec_property_naming,
1600
+ key_type=False,
1601
+ must_convert=False,
1602
+ check_type=_check_type
1603
+ )
1604
+ return converted_instance
1605
+
1606
+ if child_req_types_by_current_type == {}:
1607
+ # all types are of the required types and there are no more inner
1608
+ # variables left to look at
1609
+ return input_value
1610
+ inner_required_types = child_req_types_by_current_type.get(
1611
+ type(input_value)
1612
+ )
1613
+ if inner_required_types is None:
1614
+ # for this type, there are not more inner variables left to look at
1615
+ return input_value
1616
+ if isinstance(input_value, list):
1617
+ if input_value == []:
1618
+ # allow an empty list
1619
+ return input_value
1620
+ for index, inner_value in enumerate(input_value):
1621
+ inner_path = list(path_to_item)
1622
+ inner_path.append(index)
1623
+ input_value[index] = validate_and_convert_types(
1624
+ inner_value,
1625
+ inner_required_types,
1626
+ inner_path,
1627
+ spec_property_naming,
1628
+ _check_type,
1629
+ configuration=configuration
1630
+ )
1631
+ elif isinstance(input_value, dict):
1632
+ if input_value == {}:
1633
+ # allow an empty dict
1634
+ return input_value
1635
+ for inner_key, inner_val in input_value.items():
1636
+ inner_path = list(path_to_item)
1637
+ inner_path.append(inner_key)
1638
+ if get_simple_class(inner_key) != str:
1639
+ raise get_type_error(inner_key, inner_path, valid_classes,
1640
+ key_type=True)
1641
+ input_value[inner_key] = validate_and_convert_types(
1642
+ inner_val,
1643
+ inner_required_types,
1644
+ inner_path,
1645
+ spec_property_naming,
1646
+ _check_type,
1647
+ configuration=configuration
1648
+ )
1649
+ return input_value
1650
+
1651
+
1652
+ def model_to_dict(model_instance, serialize=True):
1653
+ """Returns the model properties as a dict
1654
+
1655
+ Args:
1656
+ model_instance (one of your model instances): the model instance that
1657
+ will be converted to a dict.
1658
+
1659
+ Keyword Args:
1660
+ serialize (bool): if True, the keys in the dict will be values from
1661
+ attribute_map
1662
+ """
1663
+ result = {}
1664
+
1665
+ model_instances = [model_instance]
1666
+ if model_instance._composed_schemas:
1667
+ model_instances.extend(model_instance._composed_instances)
1668
+ seen_json_attribute_names = set()
1669
+ used_fallback_python_attribute_names = set()
1670
+ py_to_json_map = {}
1671
+ for model_instance in model_instances:
1672
+ for attr, value in model_instance._data_store.items():
1673
+ if serialize:
1674
+ # we use get here because additional property key names do not
1675
+ # exist in attribute_map
1676
+ try:
1677
+ attr = model_instance.attribute_map[attr]
1678
+ py_to_json_map.update(model_instance.attribute_map)
1679
+ seen_json_attribute_names.add(attr)
1680
+ except KeyError:
1681
+ used_fallback_python_attribute_names.add(attr)
1682
+ if isinstance(value, list):
1683
+ if not value:
1684
+ # empty list or None
1685
+ result[attr] = value
1686
+ else:
1687
+ res = []
1688
+ for v in value:
1689
+ if isinstance(v, PRIMITIVE_TYPES) or v is None:
1690
+ res.append(v)
1691
+ elif isinstance(v, ModelSimple):
1692
+ res.append(v.value)
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
+ lambda item: (item[0],
1699
+ model_to_dict(item[1], serialize=serialize))
1700
+ if hasattr(item[1], '_data_store') else item,
1701
+ value.items()
1702
+ ))
1703
+ elif isinstance(value, ModelSimple):
1704
+ result[attr] = value.value
1705
+ elif hasattr(value, '_data_store'):
1706
+ result[attr] = model_to_dict(value, serialize=serialize)
1707
+ else:
1708
+ result[attr] = value
1709
+ if serialize:
1710
+ for python_key in used_fallback_python_attribute_names:
1711
+ json_key = py_to_json_map.get(python_key)
1712
+ if json_key is None:
1713
+ continue
1714
+ if python_key == json_key:
1715
+ continue
1716
+ json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names
1717
+ if json_key_assigned_no_need_for_python_key:
1718
+ del result[python_key]
1719
+
1720
+ return result
1721
+
1722
+
1723
+ def type_error_message(var_value=None, var_name=None, valid_classes=None,
1724
+ key_type=None):
1725
+ """
1726
+ Keyword Args:
1727
+ var_value (any): the variable which has the type_error
1728
+ var_name (str): the name of the variable which has the typ error
1729
+ valid_classes (tuple): the accepted classes for current_item's
1730
+ value
1731
+ key_type (bool): False if our value is a value in a dict
1732
+ True if it is a key in a dict
1733
+ False if our item is an item in a list
1734
+ """
1735
+ key_or_value = 'value'
1736
+ if key_type:
1737
+ key_or_value = 'key'
1738
+ valid_classes_phrase = get_valid_classes_phrase(valid_classes)
1739
+ msg = (
1740
+ "Invalid type for variable '{0}'. Required {1} type {2} and "
1741
+ "passed type was {3}".format(
1742
+ var_name,
1743
+ key_or_value,
1744
+ valid_classes_phrase,
1745
+ type(var_value).__name__,
1746
+ )
1747
+ )
1748
+ return msg
1749
+
1750
+
1751
+ def get_valid_classes_phrase(input_classes):
1752
+ """Returns a string phrase describing what types are allowed
1753
+ """
1754
+ all_classes = list(input_classes)
1755
+ all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
1756
+ all_class_names = [cls.__name__ for cls in all_classes]
1757
+ if len(all_class_names) == 1:
1758
+ return 'is {0}'.format(all_class_names[0])
1759
+ return "is one of [{0}]".format(", ".join(all_class_names))
1760
+
1761
+
1762
+ def get_allof_instances(self, model_args, constant_args):
1763
+ """
1764
+ Args:
1765
+ self: the class we are handling
1766
+ model_args (dict): var_name to var_value
1767
+ used to make instances
1768
+ constant_args (dict):
1769
+ metadata arguments:
1770
+ _check_type
1771
+ _path_to_item
1772
+ _spec_property_naming
1773
+ _configuration
1774
+ _visited_composed_classes
1775
+
1776
+ Returns
1777
+ composed_instances (list)
1778
+ """
1779
+ composed_instances = []
1780
+ for allof_class in self._composed_schemas['allOf']:
1781
+
1782
+ try:
1783
+ if constant_args.get('_spec_property_naming'):
1784
+ allof_instance = allof_class._from_openapi_data(**model_args, **constant_args)
1785
+ else:
1786
+ allof_instance = allof_class(**model_args, **constant_args)
1787
+ composed_instances.append(allof_instance)
1788
+ except Exception as ex:
1789
+ raise ApiValueError(
1790
+ "Invalid inputs given to generate an instance of '%s'. The "
1791
+ "input data was invalid for the allOf schema '%s' in the composed "
1792
+ "schema '%s'. Error=%s" % (
1793
+ allof_class.__name__,
1794
+ allof_class.__name__,
1795
+ self.__class__.__name__,
1796
+ str(ex)
1797
+ )
1798
+ ) from ex
1799
+ return composed_instances
1800
+
1801
+
1802
+ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
1803
+ """
1804
+ Find the oneOf schema that matches the input data (e.g. payload).
1805
+ If exactly one schema matches the input data, an instance of that schema
1806
+ is returned.
1807
+ If zero or more than one schema match the input data, an exception is raised.
1808
+ In OAS 3.x, the payload MUST, by validation, match exactly one of the
1809
+ schemas described by oneOf.
1810
+
1811
+ Args:
1812
+ cls: the class we are handling
1813
+ model_kwargs (dict): var_name to var_value
1814
+ The input data, e.g. the payload that must match a oneOf schema
1815
+ in the OpenAPI document.
1816
+ constant_kwargs (dict): var_name to var_value
1817
+ args that every model requires, including configuration, server
1818
+ and path to item.
1819
+
1820
+ Kwargs:
1821
+ model_arg: (int, float, bool, str, date, datetime, ModelSimple, None):
1822
+ the value to assign to a primitive class or ModelSimple class
1823
+ Notes:
1824
+ - this is only passed in when oneOf includes types which are not object
1825
+ - None is used to suppress handling of model_arg, nullable models are handled in __new__
1826
+
1827
+ Returns
1828
+ oneof_instance (instance)
1829
+ """
1830
+ if len(cls._composed_schemas['oneOf']) == 0:
1831
+ return None
1832
+
1833
+ oneof_instances = []
1834
+ # Iterate over each oneOf schema and determine if the input data
1835
+ # matches the oneOf schemas.
1836
+ for oneof_class in cls._composed_schemas['oneOf']:
1837
+ # The composed oneOf schema allows the 'null' type and the input data
1838
+ # is the null value. This is a OAS >= 3.1 feature.
1839
+ if oneof_class is none_type:
1840
+ # skip none_types because we are deserializing dict data.
1841
+ # none_type deserialization is handled in the __new__ method
1842
+ continue
1843
+
1844
+ single_value_input = allows_single_value_input(oneof_class)
1845
+
1846
+ try:
1847
+ if not single_value_input:
1848
+ if constant_kwargs.get('_spec_property_naming'):
1849
+ oneof_instance = oneof_class._from_openapi_data(
1850
+ **model_kwargs, **constant_kwargs)
1851
+ else:
1852
+ oneof_instance = oneof_class(**model_kwargs, **constant_kwargs)
1853
+ else:
1854
+ if issubclass(oneof_class, ModelSimple):
1855
+ if constant_kwargs.get('_spec_property_naming'):
1856
+ oneof_instance = oneof_class._from_openapi_data(
1857
+ model_arg, **constant_kwargs)
1858
+ else:
1859
+ oneof_instance = oneof_class(model_arg, **constant_kwargs)
1860
+ elif oneof_class in PRIMITIVE_TYPES:
1861
+ oneof_instance = validate_and_convert_types(
1862
+ model_arg,
1863
+ (oneof_class,),
1864
+ constant_kwargs['_path_to_item'],
1865
+ constant_kwargs['_spec_property_naming'],
1866
+ constant_kwargs['_check_type'],
1867
+ configuration=constant_kwargs['_configuration']
1868
+ )
1869
+ oneof_instances.append(oneof_instance)
1870
+ except Exception:
1871
+ pass
1872
+ if len(oneof_instances) == 0:
1873
+ raise ApiValueError(
1874
+ "Invalid inputs given to generate an instance of %s. None "
1875
+ "of the oneOf schemas matched the input data." %
1876
+ cls.__name__
1877
+ )
1878
+ elif len(oneof_instances) > 1:
1879
+ raise ApiValueError(
1880
+ "Invalid inputs given to generate an instance of %s. Multiple "
1881
+ "oneOf schemas matched the inputs, but a max of one is allowed." %
1882
+ cls.__name__
1883
+ )
1884
+ return oneof_instances[0]
1885
+
1886
+
1887
+ def get_anyof_instances(self, model_args, constant_args):
1888
+ """
1889
+ Args:
1890
+ self: the class we are handling
1891
+ model_args (dict): var_name to var_value
1892
+ The input data, e.g. the payload that must match at least one
1893
+ anyOf child schema in the OpenAPI document.
1894
+ constant_args (dict): var_name to var_value
1895
+ args that every model requires, including configuration, server
1896
+ and path to item.
1897
+
1898
+ Returns
1899
+ anyof_instances (list)
1900
+ """
1901
+ anyof_instances = []
1902
+ if len(self._composed_schemas['anyOf']) == 0:
1903
+ return anyof_instances
1904
+
1905
+ for anyof_class in self._composed_schemas['anyOf']:
1906
+ # The composed oneOf schema allows the 'null' type and the input data
1907
+ # is the null value. This is a OAS >= 3.1 feature.
1908
+ if anyof_class is none_type:
1909
+ # skip none_types because we are deserializing dict data.
1910
+ # none_type deserialization is handled in the __new__ method
1911
+ continue
1912
+
1913
+ try:
1914
+ if constant_args.get('_spec_property_naming'):
1915
+ anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args)
1916
+ else:
1917
+ anyof_instance = anyof_class(**model_args, **constant_args)
1918
+ anyof_instances.append(anyof_instance)
1919
+ except Exception:
1920
+ pass
1921
+ if len(anyof_instances) == 0:
1922
+ raise ApiValueError(
1923
+ "Invalid inputs given to generate an instance of %s. None of the "
1924
+ "anyOf schemas matched the inputs." %
1925
+ self.__class__.__name__
1926
+ )
1927
+ return anyof_instances
1928
+
1929
+
1930
+ def get_discarded_args(self, composed_instances, model_args):
1931
+ """
1932
+ Gathers the args that were discarded by configuration.discard_unknown_keys
1933
+ """
1934
+ model_arg_keys = model_args.keys()
1935
+ discarded_args = set()
1936
+ # arguments passed to self were already converted to python names
1937
+ # before __init__ was called
1938
+ for instance in composed_instances:
1939
+ if instance.__class__ in self._composed_schemas['allOf']:
1940
+ try:
1941
+ keys = instance.to_dict().keys()
1942
+ discarded_keys = model_args - keys
1943
+ discarded_args.update(discarded_keys)
1944
+ except Exception:
1945
+ # allOf integer schema will throw exception
1946
+ pass
1947
+ else:
1948
+ try:
1949
+ all_keys = set(model_to_dict(instance, serialize=False).keys())
1950
+ js_keys = model_to_dict(instance, serialize=True).keys()
1951
+ all_keys.update(js_keys)
1952
+ discarded_keys = model_arg_keys - all_keys
1953
+ discarded_args.update(discarded_keys)
1954
+ except Exception:
1955
+ # allOf integer schema will throw exception
1956
+ pass
1957
+ return discarded_args
1958
+
1959
+
1960
+ def validate_get_composed_info(constant_args, model_args, self):
1961
+ """
1962
+ For composed schemas, generate schema instances for
1963
+ all schemas in the oneOf/anyOf/allOf definition. If additional
1964
+ properties are allowed, also assign those properties on
1965
+ all matched schemas that contain additionalProperties.
1966
+ Openapi schemas are python classes.
1967
+
1968
+ Exceptions are raised if:
1969
+ - 0 or > 1 oneOf schema matches the model_args input data
1970
+ - no anyOf schema matches the model_args input data
1971
+ - any of the allOf schemas do not match the model_args input data
1972
+
1973
+ Args:
1974
+ constant_args (dict): these are the args that every model requires
1975
+ model_args (dict): these are the required and optional spec args that
1976
+ were passed in to make this model
1977
+ self (class): the class that we are instantiating
1978
+ This class contains self._composed_schemas
1979
+
1980
+ Returns:
1981
+ composed_info (list): length three
1982
+ composed_instances (list): the composed instances which are not
1983
+ self
1984
+ var_name_to_model_instances (dict): a dict going from var_name
1985
+ to the model_instance which holds that var_name
1986
+ the model_instance may be self or an instance of one of the
1987
+ classes in self.composed_instances()
1988
+ additional_properties_model_instances (list): a list of the
1989
+ model instances which have the property
1990
+ additional_properties_type. This list can include self
1991
+ """
1992
+ # create composed_instances
1993
+ composed_instances = []
1994
+ allof_instances = get_allof_instances(self, model_args, constant_args)
1995
+ composed_instances.extend(allof_instances)
1996
+ oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args)
1997
+ if oneof_instance is not None:
1998
+ composed_instances.append(oneof_instance)
1999
+ anyof_instances = get_anyof_instances(self, model_args, constant_args)
2000
+ composed_instances.extend(anyof_instances)
2001
+ """
2002
+ set additional_properties_model_instances
2003
+ additional properties must be evaluated at the schema level
2004
+ so self's additional properties are most important
2005
+ If self is a composed schema with:
2006
+ - no properties defined in self
2007
+ - additionalProperties: False
2008
+ Then for object payloads every property is an additional property
2009
+ and they are not allowed, so only empty dict is allowed
2010
+
2011
+ Properties must be set on all matching schemas
2012
+ so when a property is assigned toa composed instance, it must be set on all
2013
+ composed instances regardless of additionalProperties presence
2014
+ keeping it to prevent breaking changes in v5.0.1
2015
+ TODO remove cls._additional_properties_model_instances in 6.0.0
2016
+ """
2017
+ additional_properties_model_instances = []
2018
+ if self.additional_properties_type is not None:
2019
+ additional_properties_model_instances = [self]
2020
+
2021
+ """
2022
+ no need to set properties on self in here, they will be set in __init__
2023
+ By here all composed schema oneOf/anyOf/allOf instances have their properties set using
2024
+ model_args
2025
+ """
2026
+ discarded_args = get_discarded_args(self, composed_instances, model_args)
2027
+
2028
+ # map variable names to composed_instances
2029
+ var_name_to_model_instances = {}
2030
+ for prop_name in model_args:
2031
+ if prop_name not in discarded_args:
2032
+ var_name_to_model_instances[prop_name] = [self] + composed_instances
2033
+
2034
+ return [
2035
+ composed_instances,
2036
+ var_name_to_model_instances,
2037
+ additional_properties_model_instances,
2038
+ discarded_args
2039
+ ]