fds.sdk.ProposalGenerationEngine 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 (141) hide show
  1. fds/__init__.py +0 -0
  2. fds/sdk/ProposalGenerationEngine/__init__.py +28 -0
  3. fds/sdk/ProposalGenerationEngine/api/__init__.py +3 -0
  4. fds/sdk/ProposalGenerationEngine/api/ex_post_api.py +1451 -0
  5. fds/sdk/ProposalGenerationEngine/api/lookup_api.py +333 -0
  6. fds/sdk/ProposalGenerationEngine/api_client.py +939 -0
  7. fds/sdk/ProposalGenerationEngine/apis/__init__.py +18 -0
  8. fds/sdk/ProposalGenerationEngine/configuration.py +500 -0
  9. fds/sdk/ProposalGenerationEngine/exceptions.py +160 -0
  10. fds/sdk/ProposalGenerationEngine/model/__init__.py +5 -0
  11. fds/sdk/ProposalGenerationEngine/model/array.py +279 -0
  12. fds/sdk/ProposalGenerationEngine/model/backfill_data.py +264 -0
  13. fds/sdk/ProposalGenerationEngine/model/base_settings.py +264 -0
  14. fds/sdk/ProposalGenerationEngine/model/boxplot.py +266 -0
  15. fds/sdk/ProposalGenerationEngine/model/boxplot_boxplot_summary.py +284 -0
  16. fds/sdk/ProposalGenerationEngine/model/cl_pair.py +252 -0
  17. fds/sdk/ProposalGenerationEngine/model/correlation_matrix.py +260 -0
  18. fds/sdk/ProposalGenerationEngine/model/correlation_stats.py +268 -0
  19. fds/sdk/ProposalGenerationEngine/model/dated_correlation_stats.py +268 -0
  20. fds/sdk/ProposalGenerationEngine/model/dated_correlation_stats_per_time_window.py +262 -0
  21. fds/sdk/ProposalGenerationEngine/model/dated_node_stats.py +262 -0
  22. fds/sdk/ProposalGenerationEngine/model/drawdown.py +268 -0
  23. fds/sdk/ProposalGenerationEngine/model/drawdown_stats.py +290 -0
  24. fds/sdk/ProposalGenerationEngine/model/entity.py +256 -0
  25. fds/sdk/ProposalGenerationEngine/model/entity_stats.py +292 -0
  26. fds/sdk/ProposalGenerationEngine/model/error.py +274 -0
  27. fds/sdk/ProposalGenerationEngine/model/errors.py +262 -0
  28. fds/sdk/ProposalGenerationEngine/model/ex_post_period_stats.py +333 -0
  29. fds/sdk/ProposalGenerationEngine/model/ex_post_period_stats_all_of.py +262 -0
  30. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio.py +343 -0
  31. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio_all_of.py +268 -0
  32. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio_investment.py +329 -0
  33. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio_investment_all_of.py +266 -0
  34. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio_investment_response.py +357 -0
  35. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio_investment_response_all_of.py +284 -0
  36. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio_investment_series_response.py +353 -0
  37. fds/sdk/ProposalGenerationEngine/model/ex_post_portfolio_investment_series_response_all_of.py +280 -0
  38. fds/sdk/ProposalGenerationEngine/model/ex_post_rolling_settings.py +338 -0
  39. fds/sdk/ProposalGenerationEngine/model/ex_post_rolling_settings_all_of.py +280 -0
  40. fds/sdk/ProposalGenerationEngine/model/ex_post_series.py +268 -0
  41. fds/sdk/ProposalGenerationEngine/model/ex_post_series_data.py +280 -0
  42. fds/sdk/ProposalGenerationEngine/model/ex_post_series_response.py +268 -0
  43. fds/sdk/ProposalGenerationEngine/model/ex_post_series_response_data.py +272 -0
  44. fds/sdk/ProposalGenerationEngine/model/ex_post_series_response_meta.py +262 -0
  45. fds/sdk/ProposalGenerationEngine/model/ex_post_series_rolling.py +268 -0
  46. fds/sdk/ProposalGenerationEngine/model/ex_post_series_rolling_data.py +278 -0
  47. fds/sdk/ProposalGenerationEngine/model/ex_post_series_rolling_response.py +274 -0
  48. fds/sdk/ProposalGenerationEngine/model/ex_post_series_rolling_response_data.py +262 -0
  49. fds/sdk/ProposalGenerationEngine/model/ex_post_series_rolling_response_meta.py +262 -0
  50. fds/sdk/ProposalGenerationEngine/model/ex_post_series_rolling_settings.py +341 -0
  51. fds/sdk/ProposalGenerationEngine/model/ex_post_series_settings.py +353 -0
  52. fds/sdk/ProposalGenerationEngine/model/ex_post_series_settings_all_of.py +267 -0
  53. fds/sdk/ProposalGenerationEngine/model/ex_post_settings.py +355 -0
  54. fds/sdk/ProposalGenerationEngine/model/ex_post_settings_all_of.py +262 -0
  55. fds/sdk/ProposalGenerationEngine/model/ex_post_stats.py +268 -0
  56. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_correlations.py +268 -0
  57. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_correlations_data.py +280 -0
  58. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_correlations_response.py +274 -0
  59. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_correlations_response_meta.py +262 -0
  60. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_correlations_settings.py +346 -0
  61. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_correlations_settings_all_of.py +275 -0
  62. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_data.py +280 -0
  63. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_factor_exposure.py +268 -0
  64. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_factor_exposure_data.py +280 -0
  65. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_factor_exposure_response.py +274 -0
  66. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_factor_exposure_response_meta.py +262 -0
  67. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_factor_exposure_settings.py +338 -0
  68. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_factor_exposure_settings_all_of.py +267 -0
  69. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_response.py +268 -0
  70. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_response_data.py +272 -0
  71. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_response_meta.py +262 -0
  72. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_rolling.py +268 -0
  73. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_rolling_data.py +280 -0
  74. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_rolling_response.py +274 -0
  75. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_rolling_response_data.py +262 -0
  76. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_rolling_response_meta.py +262 -0
  77. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_rolling_settings.py +339 -0
  78. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_rolling_settings_all_of.py +262 -0
  79. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_settings.py +360 -0
  80. fds/sdk/ProposalGenerationEngine/model/ex_post_stats_settings_all_of.py +256 -0
  81. fds/sdk/ProposalGenerationEngine/model/exposure.py +282 -0
  82. fds/sdk/ProposalGenerationEngine/model/investment.py +343 -0
  83. fds/sdk/ProposalGenerationEngine/model/investment_all_of.py +280 -0
  84. fds/sdk/ProposalGenerationEngine/model/key_value_pair.py +260 -0
  85. fds/sdk/ProposalGenerationEngine/model/level.py +256 -0
  86. fds/sdk/ProposalGenerationEngine/model/paged_securities.py +276 -0
  87. fds/sdk/ProposalGenerationEngine/model/paged_securities_meta.py +262 -0
  88. fds/sdk/ProposalGenerationEngine/model/paged_securities_meta_pagination.py +260 -0
  89. fds/sdk/ProposalGenerationEngine/model/performance_stats.py +264 -0
  90. fds/sdk/ProposalGenerationEngine/model/period.py +260 -0
  91. fds/sdk/ProposalGenerationEngine/model/period_correlation_stats.py +333 -0
  92. fds/sdk/ProposalGenerationEngine/model/period_correlation_stats_all_of.py +262 -0
  93. fds/sdk/ProposalGenerationEngine/model/period_info.py +268 -0
  94. fds/sdk/ProposalGenerationEngine/model/period_series.py +333 -0
  95. fds/sdk/ProposalGenerationEngine/model/period_series_all_of.py +262 -0
  96. fds/sdk/ProposalGenerationEngine/model/periods.py +262 -0
  97. fds/sdk/ProposalGenerationEngine/model/portfolio.py +331 -0
  98. fds/sdk/ProposalGenerationEngine/model/portfolio_all_of.py +266 -0
  99. fds/sdk/ProposalGenerationEngine/model/portfolio_correlation_matrix.py +260 -0
  100. fds/sdk/ProposalGenerationEngine/model/portfolio_entity.py +266 -0
  101. fds/sdk/ProposalGenerationEngine/model/portfolio_entity_details.py +256 -0
  102. fds/sdk/ProposalGenerationEngine/model/portfolio_investment.py +268 -0
  103. fds/sdk/ProposalGenerationEngine/model/portfolio_with_ex_post_series.py +333 -0
  104. fds/sdk/ProposalGenerationEngine/model/portfolio_with_ex_post_series_all_of.py +268 -0
  105. fds/sdk/ProposalGenerationEngine/model/portfolio_with_ex_post_stats.py +337 -0
  106. fds/sdk/ProposalGenerationEngine/model/portfolio_with_ex_post_stats_all_of.py +272 -0
  107. fds/sdk/ProposalGenerationEngine/model/portfolio_with_rolling_series.py +327 -0
  108. fds/sdk/ProposalGenerationEngine/model/portfolio_with_rolling_series_all_of.py +262 -0
  109. fds/sdk/ProposalGenerationEngine/model/portfolio_with_rolling_stats.py +327 -0
  110. fds/sdk/ProposalGenerationEngine/model/portfolio_with_rolling_stats_all_of.py +262 -0
  111. fds/sdk/ProposalGenerationEngine/model/rebalancing.py +270 -0
  112. fds/sdk/ProposalGenerationEngine/model/relative_risk_stats.py +280 -0
  113. fds/sdk/ProposalGenerationEngine/model/return_stats.py +264 -0
  114. fds/sdk/ProposalGenerationEngine/model/risk_node_stats.py +304 -0
  115. fds/sdk/ProposalGenerationEngine/model/risk_stats.py +290 -0
  116. fds/sdk/ProposalGenerationEngine/model/rolling_series.py +262 -0
  117. fds/sdk/ProposalGenerationEngine/model/rolling_series_per_time_window.py +266 -0
  118. fds/sdk/ProposalGenerationEngine/model/rolling_series_per_time_window_returns.py +266 -0
  119. fds/sdk/ProposalGenerationEngine/model/rolling_stats.py +262 -0
  120. fds/sdk/ProposalGenerationEngine/model/rolling_stats_per_time_window.py +262 -0
  121. fds/sdk/ProposalGenerationEngine/model/rolling_stats_per_time_window_rolling.py +256 -0
  122. fds/sdk/ProposalGenerationEngine/model/serie_stats.py +282 -0
  123. fds/sdk/ProposalGenerationEngine/model/series_stats.py +266 -0
  124. fds/sdk/ProposalGenerationEngine/model/settings.py +338 -0
  125. fds/sdk/ProposalGenerationEngine/model/settings_all_of.py +269 -0
  126. fds/sdk/ProposalGenerationEngine/model/stats.py +311 -0
  127. fds/sdk/ProposalGenerationEngine/model/time_window.py +256 -0
  128. fds/sdk/ProposalGenerationEngine/model/time_window_series.py +262 -0
  129. fds/sdk/ProposalGenerationEngine/model/time_window_stats.py +268 -0
  130. fds/sdk/ProposalGenerationEngine/model/time_window_stats_generic.py +256 -0
  131. fds/sdk/ProposalGenerationEngine/model/transaction_rule.py +334 -0
  132. fds/sdk/ProposalGenerationEngine/model/ui_value_object.py +264 -0
  133. fds/sdk/ProposalGenerationEngine/model_utils.py +2062 -0
  134. fds/sdk/ProposalGenerationEngine/models/__init__.py +133 -0
  135. fds/sdk/ProposalGenerationEngine/rest.py +347 -0
  136. fds/sdk/__init__.py +0 -0
  137. fds_sdk_proposalgenerationengine-0.1.0.dist-info/METADATA +456 -0
  138. fds_sdk_proposalgenerationengine-0.1.0.dist-info/RECORD +141 -0
  139. fds_sdk_proposalgenerationengine-0.1.0.dist-info/WHEEL +5 -0
  140. fds_sdk_proposalgenerationengine-0.1.0.dist-info/licenses/LICENSE +202 -0
  141. fds_sdk_proposalgenerationengine-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2062 @@
1
+ """
2
+ Proposal Generation Engine API
3
+
4
+ Documentation on all available end points in the Proposal Generation API # noqa: E501
5
+
6
+ The version of the OpenAPI document: 0.0.1
7
+ Contact: api@factset.com
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 fds.sdk.ProposalGenerationEngine.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
+ @wraps(fn)
37
+ def wrapped_init(_self, *args, **kwargs):
38
+ """
39
+ An attribute named `self` received from the api will conflicts with the reserved `self`
40
+ parameter of a class method. During generation, `self` attributes are mapped
41
+ to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts.
42
+ """
43
+ spec_property_naming = kwargs.get('_spec_property_naming', False)
44
+ if spec_property_naming:
45
+ kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__)
46
+ return fn(_self, *args, **kwargs)
47
+ return wrapped_init
48
+
49
+
50
+ class cached_property(object):
51
+ # this caches the result of the function call for fn with no inputs
52
+ # use this as a decorator on function methods that you want converted
53
+ # into cached properties
54
+ result_key = '_results'
55
+
56
+ def __init__(self, fn):
57
+ self._fn = fn
58
+
59
+ def __get__(self, instance, cls=None):
60
+ if self.result_key in vars(self):
61
+ return vars(self)[self.result_key]
62
+ else:
63
+ result = self._fn()
64
+ setattr(self, self.result_key, result)
65
+ return result
66
+
67
+
68
+ PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type)
69
+
70
+ def allows_single_value_input(cls):
71
+ """
72
+ This function returns True if the input composed schema model or any
73
+ descendant model allows a value only input
74
+ This is true for cases where oneOf contains items like:
75
+ oneOf:
76
+ - float
77
+ - NumberWithValidation
78
+ - StringEnum
79
+ - ArrayModel
80
+ - null
81
+ TODO: lru_cache this
82
+ """
83
+ if (
84
+ issubclass(cls, ModelSimple) or
85
+ cls in PRIMITIVE_TYPES
86
+ ):
87
+ return True
88
+ elif issubclass(cls, ModelComposed):
89
+ if not cls._composed_schemas['oneOf']:
90
+ return False
91
+ return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf'])
92
+ return False
93
+
94
+ def composed_model_input_classes(cls):
95
+ """
96
+ This function returns a list of the possible models that can be accepted as
97
+ inputs.
98
+ TODO: lru_cache this
99
+ """
100
+ if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES:
101
+ return [cls]
102
+ elif issubclass(cls, ModelNormal):
103
+ if cls.discriminator is None:
104
+ return [cls]
105
+ else:
106
+ return get_discriminated_classes(cls)
107
+ elif issubclass(cls, ModelComposed):
108
+ if not cls._composed_schemas['oneOf']:
109
+ return []
110
+ if cls.discriminator is None:
111
+ input_classes = []
112
+ for c in cls._composed_schemas['oneOf']:
113
+ input_classes.extend(composed_model_input_classes(c))
114
+ return input_classes
115
+ else:
116
+ return get_discriminated_classes(cls)
117
+ return []
118
+
119
+
120
+ class OpenApiModel(object):
121
+ """The base class for all OpenAPIModels"""
122
+
123
+ def set_attribute(self, name, value):
124
+ # this is only used to set properties on self
125
+
126
+ path_to_item = []
127
+ if self._path_to_item:
128
+ path_to_item.extend(self._path_to_item)
129
+ path_to_item.append(name)
130
+
131
+ if name in self.openapi_types:
132
+ required_types_mixed = self.openapi_types[name]
133
+ elif self.additional_properties_type is None:
134
+ raise ApiAttributeError(
135
+ "{0} has no attribute '{1}'".format(
136
+ type(self).__name__, name),
137
+ path_to_item
138
+ )
139
+ elif self.additional_properties_type is not None:
140
+ required_types_mixed = self.additional_properties_type
141
+
142
+ if get_simple_class(name) != str:
143
+ error_msg = type_error_message(
144
+ var_name=name,
145
+ var_value=name,
146
+ valid_classes=(str,),
147
+ key_type=True
148
+ )
149
+ raise ApiTypeError(
150
+ error_msg,
151
+ path_to_item=path_to_item,
152
+ valid_classes=(str,),
153
+ key_type=True
154
+ )
155
+
156
+ if self._check_type:
157
+ value = validate_and_convert_types(
158
+ value, required_types_mixed, path_to_item, self._spec_property_naming,
159
+ self._check_type, configuration=self._configuration)
160
+ if (name,) in self.allowed_values:
161
+ check_allowed_values(
162
+ self.allowed_values,
163
+ (name,),
164
+ value
165
+ )
166
+ if (name,) in self.validations:
167
+ check_validations(
168
+ self.validations,
169
+ (name,),
170
+ value,
171
+ self._configuration
172
+ )
173
+ self.__dict__['_data_store'][name] = value
174
+
175
+ def __repr__(self):
176
+ """For `print` and `pprint`"""
177
+ return self.to_str()
178
+
179
+ def __ne__(self, other):
180
+ """Returns true if both objects are not equal"""
181
+ return not self == other
182
+
183
+ def __setattr__(self, attr, value):
184
+ """set the value of an attribute using dot notation: `instance.attr = val`"""
185
+ self[attr] = value
186
+
187
+ def __getattr__(self, attr):
188
+ """get the value of an attribute using dot notation: `instance.attr`"""
189
+ return self.__getitem__(attr)
190
+
191
+ def __copy__(self):
192
+ cls = self.__class__
193
+ if self.get("_spec_property_naming", False):
194
+ return cls._new_from_openapi_data(**self.__dict__)
195
+ else:
196
+ return new_cls.__new__(cls, **self.__dict__)
197
+
198
+ def __deepcopy__(self, memo):
199
+ cls = self.__class__
200
+
201
+ if self.get("_spec_property_naming", False):
202
+ new_inst = cls._new_from_openapi_data()
203
+ else:
204
+ new_inst = cls.__new__(cls)
205
+
206
+ for k, v in self.__dict__.items():
207
+ setattr(new_inst, k, deepcopy(v, memo))
208
+ return new_inst
209
+
210
+
211
+ def __new__(cls, *args, **kwargs):
212
+ # this function uses the discriminator to
213
+ # pick a new schema/class to instantiate because a discriminator
214
+ # propertyName value was passed in
215
+
216
+ if len(args) == 1:
217
+ arg = args[0]
218
+ if arg is None and is_type_nullable(cls):
219
+ # The input data is the 'null' value and the type is nullable.
220
+ return None
221
+
222
+ if issubclass(cls, ModelComposed) and allows_single_value_input(cls):
223
+ model_kwargs = {}
224
+ oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg)
225
+ return oneof_instance
226
+
227
+
228
+ visited_composed_classes = kwargs.get('_visited_composed_classes', ())
229
+ if (
230
+ cls.discriminator is None or
231
+ cls in visited_composed_classes
232
+ ):
233
+ # Use case 1: this openapi schema (cls) does not have a discriminator
234
+ # Use case 2: we have already visited this class before and are sure that we
235
+ # want to instantiate it this time. We have visited this class deserializing
236
+ # a payload with a discriminator. During that process we traveled through
237
+ # this class but did not make an instance of it. Now we are making an
238
+ # instance of a composed class which contains cls in it, so this time make an instance of cls.
239
+ #
240
+ # Here's an example of use case 2: If Animal has a discriminator
241
+ # petType and we pass in "Dog", and the class Dog
242
+ # allOf includes Animal, we move through Animal
243
+ # once using the discriminator, and pick Dog.
244
+ # Then in the composed schema dog Dog, we will make an instance of the
245
+ # Animal class (because Dal has allOf: Animal) but this time we won't travel
246
+ # through Animal's discriminator because we passed in
247
+ # _visited_composed_classes = (Animal,)
248
+
249
+ return super(OpenApiModel, cls).__new__(cls)
250
+
251
+ # Get the name and value of the discriminator property.
252
+ # The discriminator name is obtained from the discriminator meta-data
253
+ # and the discriminator value is obtained from the input data.
254
+ discr_propertyname_py = list(cls.discriminator.keys())[0]
255
+ discr_propertyname_js = cls.attribute_map[discr_propertyname_py]
256
+ if discr_propertyname_js in kwargs:
257
+ discr_value = kwargs[discr_propertyname_js]
258
+ elif discr_propertyname_py in kwargs:
259
+ discr_value = kwargs[discr_propertyname_py]
260
+ else:
261
+ # The input data does not contain the discriminator property.
262
+ path_to_item = kwargs.get('_path_to_item', ())
263
+ raise ApiValueError(
264
+ "Cannot deserialize input data due to missing discriminator. "
265
+ "The discriminator property '%s' is missing at path: %s" %
266
+ (discr_propertyname_js, path_to_item)
267
+ )
268
+
269
+ # Implementation note: the last argument to get_discriminator_class
270
+ # is a list of visited classes. get_discriminator_class may recursively
271
+ # call itself and update the list of visited classes, and the initial
272
+ # value must be an empty list. Hence not using 'visited_composed_classes'
273
+ new_cls = get_discriminator_class(
274
+ cls, discr_propertyname_py, discr_value, [])
275
+ if new_cls is None:
276
+ path_to_item = kwargs.get('_path_to_item', ())
277
+ disc_prop_value = kwargs.get(
278
+ discr_propertyname_js, kwargs.get(discr_propertyname_py))
279
+ raise ApiValueError(
280
+ "Cannot deserialize input data due to invalid discriminator "
281
+ "value. The OpenAPI document has no mapping for discriminator "
282
+ "property '%s'='%s' at path: %s" %
283
+ (discr_propertyname_js, disc_prop_value, path_to_item)
284
+ )
285
+
286
+ if new_cls in visited_composed_classes:
287
+ # if we are making an instance of a composed schema Descendent
288
+ # which allOf includes Ancestor, then Ancestor contains
289
+ # a discriminator that includes Descendent.
290
+ # So if we make an instance of Descendent, we have to make an
291
+ # instance of Ancestor to hold the allOf properties.
292
+ # This code detects that use case and makes the instance of Ancestor
293
+ # For example:
294
+ # When making an instance of Dog, _visited_composed_classes = (Dog,)
295
+ # then we make an instance of Animal to include in dog._composed_instances
296
+ # so when we are here, cls is Animal
297
+ # cls.discriminator != None
298
+ # cls not in _visited_composed_classes
299
+ # new_cls = Dog
300
+ # but we know we know that we already have Dog
301
+ # because it is in visited_composed_classes
302
+ # so make Animal here
303
+ return super(OpenApiModel, cls).__new__(cls)
304
+
305
+ # Build a list containing all oneOf and anyOf descendants.
306
+ oneof_anyof_classes = None
307
+ if cls._composed_schemas is not None:
308
+ oneof_anyof_classes = (
309
+ cls._composed_schemas.get('oneOf', ()) +
310
+ cls._composed_schemas.get('anyOf', ()))
311
+ oneof_anyof_child = new_cls in oneof_anyof_classes
312
+ kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,)
313
+
314
+ if cls._composed_schemas.get('allOf') and oneof_anyof_child:
315
+ # Validate that we can make self because when we make the
316
+ # new_cls it will not include the allOf validations in self
317
+ self_inst = super(OpenApiModel, cls).__new__(cls)
318
+ self_inst.__init__(*args, **kwargs)
319
+
320
+ if kwargs.get("_spec_property_naming", False):
321
+ # when true, implies new is from deserialization
322
+ new_inst = new_cls._new_from_openapi_data(*args, **kwargs)
323
+ else:
324
+ new_inst = new_cls.__new__(new_cls, *args, **kwargs)
325
+ new_inst.__init__(*args, **kwargs)
326
+
327
+ return new_inst
328
+
329
+
330
+ @classmethod
331
+ @convert_js_args_to_python_args
332
+ def _new_from_openapi_data(cls, *args, **kwargs):
333
+ # this function uses the discriminator to
334
+ # pick a new schema/class to instantiate because a discriminator
335
+ # propertyName value was passed in
336
+
337
+ if len(args) == 1:
338
+ arg = args[0]
339
+ if arg is None and is_type_nullable(cls):
340
+ # The input data is the 'null' value and the type is nullable.
341
+ return None
342
+
343
+ if issubclass(cls, ModelComposed) and allows_single_value_input(cls):
344
+ model_kwargs = {}
345
+ oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg)
346
+ return oneof_instance
347
+
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
+
441
+ new_inst = new_cls._new_from_openapi_data(*args, **kwargs)
442
+ return new_inst
443
+
444
+
445
+ class ModelSimple(OpenApiModel):
446
+ """the parent class of models whose type != object in their
447
+ swagger/openapi"""
448
+
449
+ def __setitem__(self, name, value):
450
+ """set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
451
+ if name in self.required_properties:
452
+ self.__dict__[name] = value
453
+ return
454
+
455
+ self.set_attribute(name, value)
456
+
457
+ def get(self, name, default=None):
458
+ """returns the value of an attribute or some default value if the attribute was not set"""
459
+ if name in self.required_properties:
460
+ return self.__dict__[name]
461
+
462
+ return self.__dict__['_data_store'].get(name, default)
463
+
464
+ def __getitem__(self, name):
465
+ """get the value of an attribute using square-bracket notation: `instance[attr]`"""
466
+ if name in self:
467
+ return self.get(name)
468
+
469
+ raise ApiAttributeError(
470
+ "{0} has no attribute '{1}'".format(
471
+ type(self).__name__, name),
472
+ [e for e in [self._path_to_item, name] if e]
473
+ )
474
+
475
+ def __contains__(self, name):
476
+ """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`"""
477
+ if name in self.required_properties:
478
+ return name in self.__dict__
479
+
480
+ return name in self.__dict__['_data_store']
481
+
482
+ def to_str(self):
483
+ """Returns the string representation of the model"""
484
+ return str(self.value)
485
+
486
+ def __eq__(self, other):
487
+ """Returns true if both objects are equal"""
488
+ if not isinstance(other, self.__class__):
489
+ return False
490
+
491
+ this_val = self._data_store['value']
492
+ that_val = other._data_store['value']
493
+ types = set()
494
+ types.add(this_val.__class__)
495
+ types.add(that_val.__class__)
496
+ vals_equal = this_val == that_val
497
+ return vals_equal
498
+
499
+
500
+ class ModelNormal(OpenApiModel):
501
+ """the parent class of models whose type == object in their
502
+ swagger/openapi"""
503
+
504
+ def __setitem__(self, name, value):
505
+ """set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
506
+ if name in self.required_properties:
507
+ self.__dict__[name] = value
508
+ return
509
+
510
+ self.set_attribute(name, value)
511
+
512
+ def get(self, name, default=None):
513
+ """returns the value of an attribute or some default value if the attribute was not set"""
514
+ if name in self.required_properties:
515
+ return self.__dict__[name]
516
+
517
+ return self.__dict__['_data_store'].get(name, default)
518
+
519
+ def __getitem__(self, name):
520
+ """get the value of an attribute using square-bracket notation: `instance[attr]`"""
521
+ if name in self:
522
+ return self.get(name)
523
+
524
+ raise ApiAttributeError(
525
+ "{0} has no attribute '{1}'".format(
526
+ type(self).__name__, name),
527
+ [e for e in [self._path_to_item, name] if e]
528
+ )
529
+
530
+ def __contains__(self, name):
531
+ """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`"""
532
+ if name in self.required_properties:
533
+ return name in self.__dict__
534
+
535
+ return name in self.__dict__['_data_store']
536
+
537
+ def to_dict(self):
538
+ """Returns the model properties as a dict"""
539
+ return model_to_dict(self, serialize=False)
540
+
541
+ def to_str(self):
542
+ """Returns the string representation of the model"""
543
+ return pprint.pformat(self.to_dict())
544
+
545
+ def __eq__(self, other):
546
+ """Returns true if both objects are equal"""
547
+ if not isinstance(other, self.__class__):
548
+ return False
549
+
550
+ if not set(self._data_store.keys()) == set(other._data_store.keys()):
551
+ return False
552
+ for _var_name, this_val in self._data_store.items():
553
+ that_val = other._data_store[_var_name]
554
+ types = set()
555
+ types.add(this_val.__class__)
556
+ types.add(that_val.__class__)
557
+ vals_equal = this_val == that_val
558
+ if not vals_equal:
559
+ return False
560
+ return True
561
+
562
+
563
+ class ModelComposed(OpenApiModel):
564
+ """the parent class of models whose type == object in their
565
+ swagger/openapi and have oneOf/allOf/anyOf
566
+
567
+ When one sets a property we use var_name_to_model_instances to store the value in
568
+ the correct class instances + run any type checking + validation code.
569
+ When one gets a property we use var_name_to_model_instances to get the value
570
+ from the correct class instances.
571
+ This allows multiple composed schemas to contain the same property with additive
572
+ constraints on the value.
573
+
574
+ _composed_schemas (dict) stores the anyOf/allOf/oneOf classes
575
+ key (str): allOf/oneOf/anyOf
576
+ value (list): the classes in the XOf definition.
577
+ Note: none_type can be included when the openapi document version >= 3.1.0
578
+ _composed_instances (list): stores a list of instances of the composed schemas
579
+ defined in _composed_schemas. When properties are accessed in the self instance,
580
+ they are returned from the self._data_store or the data stores in the instances
581
+ in self._composed_schemas
582
+ _var_name_to_model_instances (dict): maps between a variable name on self and
583
+ the composed instances (self included) which contain that data
584
+ key (str): property name
585
+ value (list): list of class instances, self or instances in _composed_instances
586
+ which contain the value that the key is referring to.
587
+ """
588
+
589
+ def __setitem__(self, name, value):
590
+ """set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
591
+ if name in self.required_properties:
592
+ self.__dict__[name] = value
593
+ return
594
+
595
+ """
596
+ Use cases:
597
+ 1. additional_properties_type is None (additionalProperties == False in spec)
598
+ Check for property presence in self.openapi_types
599
+ if not present then throw an error
600
+ if present set in self, set attribute
601
+ always set on composed schemas
602
+ 2. additional_properties_type exists
603
+ set attribute on self
604
+ always set on composed schemas
605
+ """
606
+ if self.additional_properties_type is None:
607
+ """
608
+ For an attribute to exist on a composed schema it must:
609
+ - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND
610
+ - fulfill schema_requirements in each oneOf/anyOf/allOf schemas
611
+
612
+ schema_requirements:
613
+ For an attribute to exist on a schema it must:
614
+ - be present in properties at the schema OR
615
+ - have additionalProperties unset (defaults additionalProperties = any type) OR
616
+ - have additionalProperties set
617
+ """
618
+ if name not in self.openapi_types:
619
+ raise ApiAttributeError(
620
+ "{0} has no attribute '{1}'".format(
621
+ type(self).__name__, name),
622
+ [e for e in [self._path_to_item, name] if e]
623
+ )
624
+ # attribute must be set on self and composed instances
625
+ self.set_attribute(name, value)
626
+ for model_instance in self._composed_instances:
627
+ setattr(model_instance, name, value)
628
+ if name not in self._var_name_to_model_instances:
629
+ # we assigned an additional property
630
+ self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self]
631
+ return None
632
+
633
+ __unset_attribute_value__ = object()
634
+
635
+ def get(self, name, default=None):
636
+ """returns the value of an attribute or some default value if the attribute was not set"""
637
+ if name in self.required_properties:
638
+ return self.__dict__[name]
639
+
640
+ # get the attribute from the correct instance
641
+ model_instances = self._var_name_to_model_instances.get(name)
642
+ values = []
643
+ # A composed model stores self and child (oneof/anyOf/allOf) models under
644
+ # self._var_name_to_model_instances.
645
+ # Any property must exist in self and all model instances
646
+ # The value stored in all model instances must be the same
647
+ if model_instances:
648
+ for model_instance in model_instances:
649
+ if name in model_instance._data_store:
650
+ v = model_instance._data_store[name]
651
+ if v not in values:
652
+ values.append(v)
653
+ len_values = len(values)
654
+ if len_values == 0:
655
+ return default
656
+ elif len_values == 1:
657
+ return values[0]
658
+ elif len_values > 1:
659
+ raise ApiValueError(
660
+ "Values stored for property {0} in {1} differ when looking "
661
+ "at self and self's composed instances. All values must be "
662
+ "the same".format(name, type(self).__name__),
663
+ [e for e in [self._path_to_item, name] if e]
664
+ )
665
+
666
+ def __getitem__(self, name):
667
+ """get the value of an attribute using square-bracket notation: `instance[attr]`"""
668
+ value = self.get(name, self.__unset_attribute_value__)
669
+ if value is self.__unset_attribute_value__:
670
+ raise ApiAttributeError(
671
+ "{0} has no attribute '{1}'".format(
672
+ type(self).__name__, name),
673
+ [e for e in [self._path_to_item, name] if e]
674
+ )
675
+ return value
676
+
677
+ def __contains__(self, name):
678
+ """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`"""
679
+
680
+ if name in self.required_properties:
681
+ return name in self.__dict__
682
+
683
+ model_instances = self._var_name_to_model_instances.get(
684
+ name, self._additional_properties_model_instances)
685
+
686
+ if model_instances:
687
+ for model_instance in model_instances:
688
+ if name in model_instance._data_store:
689
+ return True
690
+
691
+ return False
692
+
693
+ def to_dict(self):
694
+ """Returns the model properties as a dict"""
695
+ return model_to_dict(self, serialize=False)
696
+
697
+ def to_str(self):
698
+ """Returns the string representation of the model"""
699
+ return pprint.pformat(self.to_dict())
700
+
701
+ def __eq__(self, other):
702
+ """Returns true if both objects are equal"""
703
+ if not isinstance(other, self.__class__):
704
+ return False
705
+
706
+ if not set(self._data_store.keys()) == set(other._data_store.keys()):
707
+ return False
708
+ for _var_name, this_val in self._data_store.items():
709
+ that_val = other._data_store[_var_name]
710
+ types = set()
711
+ types.add(this_val.__class__)
712
+ types.add(that_val.__class__)
713
+ vals_equal = this_val == that_val
714
+ if not vals_equal:
715
+ return False
716
+ return True
717
+
718
+
719
+ COERCION_INDEX_BY_TYPE = {
720
+ ModelComposed: 0,
721
+ ModelNormal: 1,
722
+ ModelSimple: 2,
723
+ none_type: 3, # The type of 'None'.
724
+ list: 4,
725
+ dict: 5,
726
+ float: 6,
727
+ int: 7,
728
+ bool: 8,
729
+ datetime: 9,
730
+ date: 10,
731
+ str: 11,
732
+ file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type.
733
+ }
734
+
735
+ # these are used to limit what type conversions we try to do
736
+ # when we have a valid type already and we want to try converting
737
+ # to another type
738
+ UPCONVERSION_TYPE_PAIRS = (
739
+ (str, datetime),
740
+ (str, date),
741
+ (int, float), # A float may be serialized as an integer, e.g. '3' is a valid serialized 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
+ def get_discriminated_classes(cls):
1127
+ """
1128
+ Returns all the classes that a discriminator converts to
1129
+ TODO: lru_cache this
1130
+ """
1131
+ possible_classes = []
1132
+ key = list(cls.discriminator.keys())[0]
1133
+ if is_type_nullable(cls):
1134
+ possible_classes.append(cls)
1135
+ for discr_cls in cls.discriminator[key].values():
1136
+ if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None:
1137
+ possible_classes.extend(get_discriminated_classes(discr_cls))
1138
+ else:
1139
+ possible_classes.append(discr_cls)
1140
+ return possible_classes
1141
+
1142
+
1143
+ def get_possible_classes(cls, from_server_context):
1144
+ # TODO: lru_cache this
1145
+ possible_classes = [cls]
1146
+ if from_server_context:
1147
+ return possible_classes
1148
+ if hasattr(cls, 'discriminator') and cls.discriminator is not None:
1149
+ possible_classes = []
1150
+ possible_classes.extend(get_discriminated_classes(cls))
1151
+ elif issubclass(cls, ModelComposed):
1152
+ possible_classes.extend(composed_model_input_classes(cls))
1153
+ return possible_classes
1154
+
1155
+
1156
+ def get_required_type_classes(required_types_mixed, spec_property_naming):
1157
+ """Converts the tuple required_types into a tuple and a dict described
1158
+ below
1159
+
1160
+ Args:
1161
+ required_types_mixed (tuple/list): will contain either classes or
1162
+ instance of list or dict
1163
+ spec_property_naming (bool): if True these values came from the
1164
+ server, and we use the data types in our endpoints.
1165
+ If False, we are client side and we need to include
1166
+ oneOf and discriminator classes inside the data types in our endpoints
1167
+
1168
+ Returns:
1169
+ (valid_classes, dict_valid_class_to_child_types_mixed):
1170
+ valid_classes (tuple): the valid classes that the current item
1171
+ should be
1172
+ dict_valid_class_to_child_types_mixed (dict):
1173
+ valid_class (class): this is the key
1174
+ child_types_mixed (list/dict/tuple): describes the valid child
1175
+ types
1176
+ """
1177
+ valid_classes = []
1178
+ child_req_types_by_current_type = {}
1179
+ for required_type in required_types_mixed:
1180
+ if isinstance(required_type, list):
1181
+ valid_classes.append(list)
1182
+ child_req_types_by_current_type[list] = required_type
1183
+ elif isinstance(required_type, tuple):
1184
+ valid_classes.append(tuple)
1185
+ child_req_types_by_current_type[tuple] = required_type
1186
+ elif isinstance(required_type, dict):
1187
+ valid_classes.append(dict)
1188
+ child_req_types_by_current_type[dict] = required_type[str]
1189
+ else:
1190
+ valid_classes.extend(get_possible_classes(required_type, spec_property_naming))
1191
+ return tuple(valid_classes), child_req_types_by_current_type
1192
+
1193
+
1194
+ def change_keys_js_to_python(input_dict, model_class):
1195
+ """
1196
+ Converts from javascript_key keys in the input_dict to python_keys in
1197
+ the output dict using the mapping in model_class.
1198
+ If the input_dict contains a key which does not declared in the model_class,
1199
+ the key is added to the output dict as is. The assumption is the model_class
1200
+ may have undeclared properties (additionalProperties attribute in the OAS
1201
+ document).
1202
+ """
1203
+
1204
+ if getattr(model_class, 'attribute_map', None) is None:
1205
+ return input_dict
1206
+ output_dict = {}
1207
+ reversed_attr_map = {value: key for key, value in
1208
+ model_class.attribute_map.items()}
1209
+ for javascript_key, value in input_dict.items():
1210
+ python_key = reversed_attr_map.get(javascript_key)
1211
+ if python_key is None:
1212
+ # if the key is unknown, it is in error or it is an
1213
+ # additionalProperties variable
1214
+ python_key = javascript_key
1215
+ output_dict[python_key] = value
1216
+ return output_dict
1217
+
1218
+
1219
+ def get_type_error(var_value, path_to_item, valid_classes, key_type=False):
1220
+ error_msg = type_error_message(
1221
+ var_name=path_to_item[-1],
1222
+ var_value=var_value,
1223
+ valid_classes=valid_classes,
1224
+ key_type=key_type
1225
+ )
1226
+ return ApiTypeError(
1227
+ error_msg,
1228
+ path_to_item=path_to_item,
1229
+ valid_classes=valid_classes,
1230
+ key_type=key_type
1231
+ )
1232
+
1233
+
1234
+ def deserialize_primitive(data, klass, path_to_item):
1235
+ """Deserializes string to primitive type.
1236
+
1237
+ :param data: str/int/float
1238
+ :param klass: str/class the class to convert to
1239
+
1240
+ :return: int, float, str, bool, date, datetime
1241
+ """
1242
+ additional_message = ""
1243
+ try:
1244
+ if klass in {datetime, date}:
1245
+ additional_message = (
1246
+ "If you need your parameter to have a fallback "
1247
+ "string value, please set its type as `type: {}` in your "
1248
+ "spec. That allows the value to be any type. "
1249
+ )
1250
+ if klass == datetime:
1251
+ if len(data) < 8:
1252
+ raise ValueError("This is not a datetime")
1253
+ # The string should be in iso8601 datetime format.
1254
+ parsed_datetime = parse(data)
1255
+ date_only = (
1256
+ parsed_datetime.hour == 0 and
1257
+ parsed_datetime.minute == 0 and
1258
+ parsed_datetime.second == 0 and
1259
+ parsed_datetime.tzinfo is None and
1260
+ 8 <= len(data) <= 10
1261
+ )
1262
+ if date_only:
1263
+ raise ValueError("This is a date, not a datetime")
1264
+ return parsed_datetime
1265
+ elif klass == date:
1266
+ if len(data) < 8:
1267
+ raise ValueError("This is not a date")
1268
+ return parse(data).date()
1269
+ else:
1270
+ converted_value = klass(data)
1271
+ if isinstance(data, str) and klass == float:
1272
+ if str(converted_value) != data:
1273
+ # '7' -> 7.0 -> '7.0' != '7'
1274
+ raise ValueError('This is not a float')
1275
+ return converted_value
1276
+ except (OverflowError, ValueError) as ex:
1277
+ # parse can raise OverflowError
1278
+ raise ApiValueError(
1279
+ "{0}Failed to parse {1} as {2}".format(
1280
+ additional_message, repr(data), klass.__name__
1281
+ ),
1282
+ path_to_item=path_to_item
1283
+ ) from ex
1284
+
1285
+
1286
+ def get_discriminator_class(model_class,
1287
+ discr_name,
1288
+ discr_value, cls_visited):
1289
+ """Returns the child class specified by the discriminator.
1290
+
1291
+ Args:
1292
+ model_class (OpenApiModel): the model class.
1293
+ discr_name (string): the name of the discriminator property.
1294
+ discr_value (any): the discriminator value.
1295
+ cls_visited (list): list of model classes that have been visited.
1296
+ Used to determine the discriminator class without
1297
+ visiting circular references indefinitely.
1298
+
1299
+ Returns:
1300
+ used_model_class (class/None): the chosen child class that will be used
1301
+ to deserialize the data, for example dog.Dog.
1302
+ If a class is not found, None is returned.
1303
+ """
1304
+
1305
+ if model_class in cls_visited:
1306
+ # The class has already been visited and no suitable class was found.
1307
+ return None
1308
+ cls_visited.append(model_class)
1309
+ used_model_class = None
1310
+ if discr_name in model_class.discriminator:
1311
+ class_name_to_discr_class = model_class.discriminator[discr_name]
1312
+ used_model_class = class_name_to_discr_class.get(discr_value)
1313
+ if used_model_class is None:
1314
+ # We didn't find a discriminated class in class_name_to_discr_class.
1315
+ # So look in the ancestor or descendant discriminators
1316
+ # The discriminator mapping may exist in a descendant (anyOf, oneOf)
1317
+ # or ancestor (allOf).
1318
+ # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat
1319
+ # hierarchy, the discriminator mappings may be defined at any level
1320
+ # in the hierarchy.
1321
+ # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig
1322
+ # if we try to make BasquePig from mammal, we need to travel through
1323
+ # the oneOf descendant discriminators to find BasquePig
1324
+ descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \
1325
+ model_class._composed_schemas.get('anyOf', ())
1326
+ ancestor_classes = model_class._composed_schemas.get('allOf', ())
1327
+ possible_classes = descendant_classes + ancestor_classes
1328
+ for cls in possible_classes:
1329
+ # Check if the schema has inherited discriminators.
1330
+ if hasattr(cls, 'discriminator') and cls.discriminator is not None:
1331
+ used_model_class = get_discriminator_class(
1332
+ cls, discr_name, discr_value, cls_visited)
1333
+ if used_model_class is not None:
1334
+ return used_model_class
1335
+ return used_model_class
1336
+
1337
+
1338
+ def deserialize_model(model_data, model_class, path_to_item, check_type,
1339
+ configuration, spec_property_naming):
1340
+ """Deserializes model_data to model instance.
1341
+
1342
+ Args:
1343
+ model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model
1344
+ model_class (OpenApiModel): the model class
1345
+ path_to_item (list): path to the model in the received data
1346
+ check_type (bool): whether to check the data tupe for the values in
1347
+ the model
1348
+ configuration (Configuration): the instance to use to convert files
1349
+ spec_property_naming (bool): True if the variable names in the input
1350
+ data are serialized names as specified in the OpenAPI document.
1351
+ False if the variables names in the input data are python
1352
+ variable names in PEP-8 snake case.
1353
+
1354
+ Returns:
1355
+ model instance
1356
+
1357
+ Raise:
1358
+ ApiTypeError
1359
+ ApiValueError
1360
+ ApiKeyError
1361
+ """
1362
+
1363
+ kw_args = dict(_check_type=check_type,
1364
+ _path_to_item=path_to_item,
1365
+ _configuration=configuration,
1366
+ _spec_property_naming=spec_property_naming)
1367
+
1368
+ if issubclass(model_class, ModelSimple):
1369
+ return model_class._new_from_openapi_data(model_data, **kw_args)
1370
+ if isinstance(model_data, dict):
1371
+ kw_args.update(model_data)
1372
+ return model_class._new_from_openapi_data(**kw_args)
1373
+ elif isinstance(model_data, PRIMITIVE_TYPES):
1374
+ return model_class._new_from_openapi_data(model_data, **kw_args)
1375
+
1376
+
1377
+ def deserialize_file(response_data, configuration, content_disposition=None):
1378
+ """Deserializes body to file
1379
+
1380
+ Saves response body into a file in a temporary folder,
1381
+ using the filename from the `Content-Disposition` header if provided.
1382
+
1383
+ Args:
1384
+ param response_data (str): the file data to write
1385
+ configuration (Configuration): the instance to use to convert files
1386
+
1387
+ Keyword Args:
1388
+ content_disposition (str): the value of the Content-Disposition
1389
+ header
1390
+
1391
+ Returns:
1392
+ (file_type): the deserialized file which is open
1393
+ The user is responsible for closing and reading the file
1394
+ """
1395
+ filename = None
1396
+
1397
+ if content_disposition:
1398
+ matcher = re.search(r'filename=[\'"]?([^\'"\s]+[^;\'"\s])[\'"]?',
1399
+ content_disposition)
1400
+ if matcher:
1401
+ filename = matcher.group(1)
1402
+
1403
+ prefix, suffix = None, None
1404
+ if filename == None:
1405
+ prefix = 'download-'
1406
+ suffix = ''
1407
+ else:
1408
+ pos = filename.rfind('.')
1409
+ if pos == -1:
1410
+ prefix = f'{filename}-'
1411
+ else:
1412
+ prefix = f'{filename[:pos]}-'
1413
+ suffix = filename[pos:]
1414
+
1415
+ fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path, suffix=suffix, prefix=prefix)
1416
+
1417
+ with os.fdopen(fd, "wb") as f:
1418
+ if isinstance(response_data, str):
1419
+ # change str to bytes so we can write it
1420
+ response_data = response_data.encode('utf-8')
1421
+ f.write(response_data)
1422
+
1423
+ f = open(path, "rb")
1424
+ return f
1425
+
1426
+
1427
+ def attempt_convert_item(input_value, valid_classes, path_to_item,
1428
+ configuration, spec_property_naming, key_type=False,
1429
+ must_convert=False, check_type=True):
1430
+ """
1431
+ Args:
1432
+ input_value (any): the data to convert
1433
+ valid_classes (any): the classes that are valid
1434
+ path_to_item (list): the path to the item to convert
1435
+ configuration (Configuration): the instance to use to convert files
1436
+ spec_property_naming (bool): True if the variable names in the input
1437
+ data are serialized names as specified in the OpenAPI document.
1438
+ False if the variables names in the input data are python
1439
+ variable names in PEP-8 snake case.
1440
+ key_type (bool): if True we need to convert a key type (not supported)
1441
+ must_convert (bool): if True we must convert
1442
+ check_type (bool): if True we check the type or the returned data in
1443
+ ModelComposed/ModelNormal/ModelSimple instances
1444
+
1445
+ Returns:
1446
+ instance (any) the fixed item
1447
+
1448
+ Raises:
1449
+ ApiTypeError
1450
+ ApiValueError
1451
+ ApiKeyError
1452
+ """
1453
+ valid_classes_ordered = order_response_types(valid_classes)
1454
+ valid_classes_coercible = remove_uncoercible(
1455
+ valid_classes_ordered, input_value, spec_property_naming)
1456
+ if not valid_classes_coercible or key_type:
1457
+ # we do not handle keytype errors, json will take care
1458
+ # of this for us
1459
+ if must_convert or configuration is None or not configuration.discard_unknown_keys:
1460
+ raise get_type_error(input_value, path_to_item, valid_classes,
1461
+ key_type=key_type)
1462
+ for valid_class in valid_classes_coercible:
1463
+ try:
1464
+ if issubclass(valid_class, OpenApiModel):
1465
+ return deserialize_model(input_value, valid_class,
1466
+ path_to_item, check_type,
1467
+ configuration, spec_property_naming)
1468
+ elif valid_class == file_type:
1469
+ return deserialize_file(input_value, configuration)
1470
+ return deserialize_primitive(input_value, valid_class,
1471
+ path_to_item)
1472
+ except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc:
1473
+ if must_convert:
1474
+ raise conversion_exc
1475
+ # if we have conversion errors when must_convert == False
1476
+ # we ignore the exception and move on to the next class
1477
+ continue
1478
+ # we were unable to convert, must_convert == False
1479
+ return input_value
1480
+
1481
+
1482
+ def is_type_nullable(input_type):
1483
+ """
1484
+ Returns true if None is an allowed value for the specified input_type.
1485
+
1486
+ A type is nullable if at least one of the following conditions is true:
1487
+ 1. The OAS 'nullable' attribute has been specified,
1488
+ 1. The type is the 'null' type,
1489
+ 1. The type is a anyOf/oneOf composed schema, and a child schema is
1490
+ the 'null' type.
1491
+ Args:
1492
+ input_type (type): the class of the input_value that we are
1493
+ checking
1494
+ Returns:
1495
+ bool
1496
+ """
1497
+ if input_type is none_type:
1498
+ return True
1499
+ if issubclass(input_type, OpenApiModel) and input_type._nullable:
1500
+ return True
1501
+ if issubclass(input_type, ModelComposed):
1502
+ # If oneOf/anyOf, check if the 'null' type is one of the allowed types.
1503
+ for t in input_type._composed_schemas.get('oneOf', ()):
1504
+ if is_type_nullable(t): return True
1505
+ for t in input_type._composed_schemas.get('anyOf', ()):
1506
+ if is_type_nullable(t): return True
1507
+ return False
1508
+
1509
+
1510
+ def is_valid_type(input_class_simple, valid_classes):
1511
+ """
1512
+ Args:
1513
+ input_class_simple (class): the class of the input_value that we are
1514
+ checking
1515
+ valid_classes (tuple): the valid classes that the current item
1516
+ should be
1517
+ Returns:
1518
+ bool
1519
+ """
1520
+ if issubclass(input_class_simple, OpenApiModel) and \
1521
+ valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,):
1522
+ return True
1523
+ valid_type = input_class_simple in valid_classes
1524
+ if not valid_type and (
1525
+ issubclass(input_class_simple, OpenApiModel) or
1526
+ input_class_simple is none_type):
1527
+ for valid_class in valid_classes:
1528
+ if input_class_simple is none_type and is_type_nullable(valid_class):
1529
+ # Schema is oneOf/anyOf and the 'null' type is one of the allowed types.
1530
+ return True
1531
+ if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator):
1532
+ continue
1533
+ discr_propertyname_py = list(valid_class.discriminator.keys())[0]
1534
+ discriminator_classes = (
1535
+ valid_class.discriminator[discr_propertyname_py].values()
1536
+ )
1537
+ valid_type = is_valid_type(input_class_simple, discriminator_classes)
1538
+ if valid_type:
1539
+ return True
1540
+ return valid_type
1541
+
1542
+
1543
+ def validate_and_convert_types(input_value, required_types_mixed, path_to_item,
1544
+ spec_property_naming, _check_type, configuration=None):
1545
+ """Raises a TypeError is there is a problem, otherwise returns value
1546
+
1547
+ Args:
1548
+ input_value (any): the data to validate/convert
1549
+ required_types_mixed (list/dict/tuple): A list of
1550
+ valid classes, or a list tuples of valid classes, or a dict where
1551
+ the value is a tuple of value classes
1552
+ path_to_item: (list) the path to the data being validated
1553
+ this stores a list of keys or indices to get to the data being
1554
+ validated
1555
+ spec_property_naming (bool): True if the variable names in the input
1556
+ data are serialized names as specified in the OpenAPI document.
1557
+ False if the variables names in the input data are python
1558
+ variable names in PEP-8 snake case.
1559
+ _check_type: (boolean) if true, type will be checked and conversion
1560
+ will be attempted.
1561
+ configuration: (Configuration): the configuration class to use
1562
+ when converting file_type items.
1563
+ If passed, conversion will be attempted when possible
1564
+ If not passed, no conversions will be attempted and
1565
+ exceptions will be raised
1566
+
1567
+ Returns:
1568
+ the correctly typed value
1569
+
1570
+ Raises:
1571
+ ApiTypeError
1572
+ """
1573
+ results = get_required_type_classes(required_types_mixed, spec_property_naming)
1574
+ valid_classes, child_req_types_by_current_type = results
1575
+
1576
+ input_class_simple = get_simple_class(input_value)
1577
+ valid_type = is_valid_type(input_class_simple, valid_classes)
1578
+ if not valid_type:
1579
+ if configuration:
1580
+ # if input_value is not valid_type try to convert it
1581
+ converted_instance = attempt_convert_item(
1582
+ input_value,
1583
+ valid_classes,
1584
+ path_to_item,
1585
+ configuration,
1586
+ spec_property_naming,
1587
+ key_type=False,
1588
+ must_convert=True,
1589
+ check_type=_check_type
1590
+ )
1591
+ return converted_instance
1592
+ else:
1593
+ raise get_type_error(input_value, path_to_item, valid_classes,
1594
+ key_type=False)
1595
+
1596
+ # input_value's type is in valid_classes
1597
+ if len(valid_classes) > 1 and configuration:
1598
+ # there are valid classes which are not the current class
1599
+ valid_classes_coercible = remove_uncoercible(
1600
+ valid_classes, input_value, spec_property_naming, must_convert=False)
1601
+ if valid_classes_coercible:
1602
+ converted_instance = attempt_convert_item(
1603
+ input_value,
1604
+ valid_classes_coercible,
1605
+ path_to_item,
1606
+ configuration,
1607
+ spec_property_naming,
1608
+ key_type=False,
1609
+ must_convert=False,
1610
+ check_type=_check_type
1611
+ )
1612
+ return converted_instance
1613
+
1614
+ if child_req_types_by_current_type == {}:
1615
+ # all types are of the required types and there are no more inner
1616
+ # variables left to look at
1617
+ return input_value
1618
+ inner_required_types = child_req_types_by_current_type.get(
1619
+ type(input_value)
1620
+ )
1621
+ if inner_required_types is None:
1622
+ # for this type, there are not more inner variables left to look at
1623
+ return input_value
1624
+ if isinstance(input_value, list):
1625
+ if input_value == []:
1626
+ # allow an empty list
1627
+ return input_value
1628
+ for index, inner_value in enumerate(input_value):
1629
+ inner_path = list(path_to_item)
1630
+ inner_path.append(index)
1631
+ input_value[index] = validate_and_convert_types(
1632
+ inner_value,
1633
+ inner_required_types,
1634
+ inner_path,
1635
+ spec_property_naming,
1636
+ _check_type,
1637
+ configuration=configuration
1638
+ )
1639
+ elif isinstance(input_value, dict):
1640
+ if input_value == {}:
1641
+ # allow an empty dict
1642
+ return input_value
1643
+ for inner_key, inner_val in input_value.items():
1644
+ inner_path = list(path_to_item)
1645
+ inner_path.append(inner_key)
1646
+ if get_simple_class(inner_key) != str:
1647
+ raise get_type_error(inner_key, inner_path, valid_classes,
1648
+ key_type=True)
1649
+ input_value[inner_key] = validate_and_convert_types(
1650
+ inner_val,
1651
+ inner_required_types,
1652
+ inner_path,
1653
+ spec_property_naming,
1654
+ _check_type,
1655
+ configuration=configuration
1656
+ )
1657
+ return input_value
1658
+
1659
+
1660
+ def model_to_dict(model_instance, serialize=True):
1661
+ """Returns the model properties as a dict
1662
+
1663
+ Args:
1664
+ model_instance (one of your model instances): the model instance that
1665
+ will be converted to a dict.
1666
+
1667
+ Keyword Args:
1668
+ serialize (bool): if True, the keys in the dict will be values from
1669
+ attribute_map
1670
+ """
1671
+ result = {}
1672
+ extract_item = lambda item: (item[0], model_to_dict(item[1], serialize=serialize)) if hasattr(item[1], '_data_store') else item
1673
+
1674
+ model_instances = [model_instance]
1675
+ if model_instance._composed_schemas:
1676
+ model_instances.extend(model_instance._composed_instances)
1677
+ seen_json_attribute_names = set()
1678
+ used_fallback_python_attribute_names = set()
1679
+ py_to_json_map = {}
1680
+ for model_instance in model_instances:
1681
+ for attr, value in model_instance._data_store.items():
1682
+ if serialize:
1683
+ # we use get here because additional property key names do not
1684
+ # exist in attribute_map
1685
+ try:
1686
+ attr = model_instance.attribute_map[attr]
1687
+ py_to_json_map.update(model_instance.attribute_map)
1688
+ seen_json_attribute_names.add(attr)
1689
+ except KeyError:
1690
+ used_fallback_python_attribute_names.add(attr)
1691
+ if isinstance(value, list):
1692
+ if not value:
1693
+ # empty list or None
1694
+ result[attr] = value
1695
+ else:
1696
+ res = []
1697
+ for v in value:
1698
+ if isinstance(v, PRIMITIVE_TYPES) or v is None:
1699
+ res.append(v)
1700
+ elif isinstance(v, ModelSimple):
1701
+ res.append(v.value)
1702
+ elif isinstance(v, dict):
1703
+ res.append(dict(map(
1704
+ extract_item,
1705
+ v.items()
1706
+ )))
1707
+ else:
1708
+ res.append(model_to_dict(v, serialize=serialize))
1709
+ result[attr] = res
1710
+ elif isinstance(value, dict):
1711
+ result[attr] = dict(map(
1712
+ extract_item,
1713
+ value.items()
1714
+ ))
1715
+ elif isinstance(value, ModelSimple):
1716
+ result[attr] = value.value
1717
+ elif hasattr(value, '_data_store'):
1718
+ result[attr] = model_to_dict(value, serialize=serialize)
1719
+ else:
1720
+ result[attr] = value
1721
+ if serialize:
1722
+ for python_key in used_fallback_python_attribute_names:
1723
+ json_key = py_to_json_map.get(python_key)
1724
+ if json_key is None:
1725
+ continue
1726
+ if python_key == json_key:
1727
+ continue
1728
+ json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names
1729
+ if json_key_assigned_no_need_for_python_key:
1730
+ del result[python_key]
1731
+
1732
+ return result
1733
+
1734
+
1735
+ def type_error_message(var_value=None, var_name=None, valid_classes=None,
1736
+ key_type=None):
1737
+ """
1738
+ Keyword Args:
1739
+ var_value (any): the variable which has the type_error
1740
+ var_name (str): the name of the variable which has the typ error
1741
+ valid_classes (tuple): the accepted classes for current_item's
1742
+ value
1743
+ key_type (bool): False if our value is a value in a dict
1744
+ True if it is a key in a dict
1745
+ False if our item is an item in a list
1746
+ """
1747
+ key_or_value = 'value'
1748
+ if key_type:
1749
+ key_or_value = 'key'
1750
+ valid_classes_phrase = get_valid_classes_phrase(valid_classes)
1751
+ msg = (
1752
+ "Invalid type for variable '{0}'. Required {1} type {2} and "
1753
+ "passed type was {3}".format(
1754
+ var_name,
1755
+ key_or_value,
1756
+ valid_classes_phrase,
1757
+ get_full_classname(type(var_value)),
1758
+ )
1759
+ )
1760
+ return msg
1761
+
1762
+
1763
+ def get_valid_classes_phrase(input_classes):
1764
+ """Returns a string phrase describing what types are allowed
1765
+ """
1766
+ all_classes = list(input_classes)
1767
+ all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
1768
+ all_class_names = [get_full_classname(cls) for cls in all_classes]
1769
+ if len(all_class_names) == 1:
1770
+ return 'is {0}'.format(all_class_names[0])
1771
+ return "is one of [{0}]".format(", ".join(all_class_names))
1772
+
1773
+
1774
+ def get_full_classname(cls):
1775
+ """Returns the fully qualified class name of the class."""
1776
+
1777
+ module = cls.__module__
1778
+ name = cls.__qualname__
1779
+ if module is not None and module != "__builtin__":
1780
+ name = module + "." + name
1781
+ return name
1782
+
1783
+
1784
+ def get_allof_instances(self, model_args, constant_args):
1785
+ """
1786
+ Args:
1787
+ self: the class we are handling
1788
+ model_args (dict): var_name to var_value
1789
+ used to make instances
1790
+ constant_args (dict):
1791
+ metadata arguments:
1792
+ _check_type
1793
+ _path_to_item
1794
+ _spec_property_naming
1795
+ _configuration
1796
+ _visited_composed_classes
1797
+
1798
+ Returns
1799
+ composed_instances (list)
1800
+ """
1801
+ composed_instances = []
1802
+ for allof_class in self._composed_schemas['allOf']:
1803
+
1804
+ try:
1805
+ if constant_args.get('_spec_property_naming'):
1806
+ allof_instance = allof_class._from_openapi_data(**model_args, **constant_args)
1807
+ else:
1808
+ allof_instance = allof_class(**model_args, **constant_args)
1809
+ composed_instances.append(allof_instance)
1810
+ except Exception as ex:
1811
+ raise ApiValueError(
1812
+ "Invalid inputs given to generate an instance of '%s'. The "
1813
+ "input data was invalid for the allOf schema '%s' in the composed "
1814
+ "schema '%s'. Error=%s" % (
1815
+ allof_class.__name__,
1816
+ allof_class.__name__,
1817
+ self.__class__.__name__,
1818
+ str(ex)
1819
+ )
1820
+ ) from ex
1821
+ return composed_instances
1822
+
1823
+
1824
+ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
1825
+ """
1826
+ Find the oneOf schema that matches the input data (e.g. payload).
1827
+ If exactly one schema matches the input data, an instance of that schema
1828
+ is returned.
1829
+ If zero or more than one schema match the input data, an exception is raised.
1830
+ In OAS 3.x, the payload MUST, by validation, match exactly one of the
1831
+ schemas described by oneOf.
1832
+
1833
+ Args:
1834
+ cls: the class we are handling
1835
+ model_kwargs (dict): var_name to var_value
1836
+ The input data, e.g. the payload that must match a oneOf schema
1837
+ in the OpenAPI document.
1838
+ constant_kwargs (dict): var_name to var_value
1839
+ args that every model requires, including configuration, server
1840
+ and path to item.
1841
+
1842
+ Kwargs:
1843
+ model_arg: (int, float, bool, str, date, datetime, ModelSimple, None):
1844
+ the value to assign to a primitive class or ModelSimple class
1845
+ Notes:
1846
+ - this is only passed in when oneOf includes types which are not object
1847
+ - None is used to suppress handling of model_arg, nullable models are handled in __new__
1848
+
1849
+ Returns
1850
+ oneof_instance (instance)
1851
+ """
1852
+ if len(cls._composed_schemas['oneOf']) == 0:
1853
+ return None
1854
+
1855
+ oneof_instances = []
1856
+ # Iterate over each oneOf schema and determine if the input data
1857
+ # matches the oneOf schemas.
1858
+ for oneof_class in cls._composed_schemas['oneOf']:
1859
+ # The composed oneOf schema allows the 'null' type and the input data
1860
+ # is the null value. This is a OAS >= 3.1 feature.
1861
+ if oneof_class is none_type:
1862
+ # skip none_types because we are deserializing dict data.
1863
+ # none_type deserialization is handled in the __new__ method
1864
+ continue
1865
+
1866
+ single_value_input = allows_single_value_input(oneof_class)
1867
+
1868
+ try:
1869
+ if not single_value_input:
1870
+ if model_arg is not None:
1871
+ continue;
1872
+ if constant_kwargs.get('_spec_property_naming'):
1873
+ oneof_instance = oneof_class._new_from_openapi_data(**model_kwargs, **constant_kwargs)
1874
+ else:
1875
+ oneof_instance = oneof_class(**model_kwargs, **constant_kwargs)
1876
+ else:
1877
+ if issubclass(oneof_class, ModelSimple):
1878
+ if constant_kwargs.get('_spec_property_naming'):
1879
+ oneof_instance = oneof_class._new_from_openapi_data(model_arg, **constant_kwargs)
1880
+ else:
1881
+ oneof_instance = oneof_class(model_arg, **constant_kwargs)
1882
+ elif oneof_class in PRIMITIVE_TYPES:
1883
+ oneof_instance = validate_and_convert_types(
1884
+ model_arg,
1885
+ (oneof_class,),
1886
+ constant_kwargs['_path_to_item'],
1887
+ constant_kwargs['_spec_property_naming'],
1888
+ constant_kwargs['_check_type'],
1889
+ configuration=constant_kwargs['_configuration']
1890
+ )
1891
+ oneof_instances.append((oneof_class, oneof_instance))
1892
+ except Exception:
1893
+ pass
1894
+ if len(oneof_instances) == 0:
1895
+ raise ApiValueError(
1896
+ "Invalid inputs given to generate an instance of %s. None "
1897
+ "of the oneOf schemas matched the input data." %
1898
+ cls.__name__
1899
+ )
1900
+ elif len(oneof_instances) > 1:
1901
+ raise ApiValueError(
1902
+ "Invalid inputs given to generate an instance of %s. Multiple "
1903
+ "oneOf schemas matched the inputs, but a max of one is allowed. "
1904
+ "Candidates: %s" %
1905
+ (cls.__name__, oneof_instances)
1906
+ )
1907
+ return oneof_instances[0][1]
1908
+
1909
+
1910
+ def get_anyof_instances(self, model_args, constant_args):
1911
+ """
1912
+ Args:
1913
+ self: the class we are handling
1914
+ model_args (dict): var_name to var_value
1915
+ The input data, e.g. the payload that must match at least one
1916
+ anyOf child schema in the OpenAPI document.
1917
+ constant_args (dict): var_name to var_value
1918
+ args that every model requires, including configuration, server
1919
+ and path to item.
1920
+
1921
+ Returns
1922
+ anyof_instances (list)
1923
+ """
1924
+ anyof_instances = []
1925
+ if len(self._composed_schemas['anyOf']) == 0:
1926
+ return anyof_instances
1927
+
1928
+ for anyof_class in self._composed_schemas['anyOf']:
1929
+ # The composed oneOf schema allows the 'null' type and the input data
1930
+ # is the null value. This is a OAS >= 3.1 feature.
1931
+ if anyof_class is none_type:
1932
+ # skip none_types because we are deserializing dict data.
1933
+ # none_type deserialization is handled in the __new__ method
1934
+ continue
1935
+
1936
+ try:
1937
+ if constant_args.get('_spec_property_naming'):
1938
+ anyof_instance = anyof_class._new_from_openapi_data(**model_args, **constant_args)
1939
+ else:
1940
+ anyof_instance = anyof_class(**model_args, **constant_args)
1941
+ anyof_instances.append(anyof_instance)
1942
+ except Exception:
1943
+ pass
1944
+ if len(anyof_instances) == 0:
1945
+ raise ApiValueError(
1946
+ "Invalid inputs given to generate an instance of %s. None of the "
1947
+ "anyOf schemas matched the inputs." %
1948
+ self.__class__.__name__
1949
+ )
1950
+ return anyof_instances
1951
+
1952
+
1953
+ def get_discarded_args(self, composed_instances, model_args):
1954
+ """
1955
+ Gathers the args that were discarded by configuration.discard_unknown_keys
1956
+ """
1957
+ model_arg_keys = model_args.keys()
1958
+ discarded_args = set()
1959
+ # arguments passed to self were already converted to python names
1960
+ # before __init__ was called
1961
+ for instance in composed_instances:
1962
+ if instance.__class__ in self._composed_schemas['allOf']:
1963
+ try:
1964
+ keys = instance.to_dict().keys()
1965
+ discarded_keys = model_args - keys
1966
+ discarded_args.update(discarded_keys)
1967
+ except Exception:
1968
+ # allOf integer schema will throw exception
1969
+ pass
1970
+ else:
1971
+ try:
1972
+ all_keys = set(model_to_dict(instance, serialize=False).keys())
1973
+ js_keys = model_to_dict(instance, serialize=True).keys()
1974
+ all_keys.update(js_keys)
1975
+ discarded_keys = model_arg_keys - all_keys
1976
+ discarded_args.update(discarded_keys)
1977
+ except Exception:
1978
+ # allOf integer schema will throw exception
1979
+ pass
1980
+ return discarded_args
1981
+
1982
+
1983
+ def validate_get_composed_info(constant_args, model_args, self):
1984
+ """
1985
+ For composed schemas, generate schema instances for
1986
+ all schemas in the oneOf/anyOf/allOf definition. If additional
1987
+ properties are allowed, also assign those properties on
1988
+ all matched schemas that contain additionalProperties.
1989
+ Openapi schemas are python classes.
1990
+
1991
+ Exceptions are raised if:
1992
+ - 0 or > 1 oneOf schema matches the model_args input data
1993
+ - no anyOf schema matches the model_args input data
1994
+ - any of the allOf schemas do not match the model_args input data
1995
+
1996
+ Args:
1997
+ constant_args (dict): these are the args that every model requires
1998
+ model_args (dict): these are the required and optional spec args that
1999
+ were passed in to make this model
2000
+ self (class): the class that we are instantiating
2001
+ This class contains self._composed_schemas
2002
+
2003
+ Returns:
2004
+ composed_info (list): length three
2005
+ composed_instances (list): the composed instances which are not
2006
+ self
2007
+ var_name_to_model_instances (dict): a dict going from var_name
2008
+ to the model_instance which holds that var_name
2009
+ the model_instance may be self or an instance of one of the
2010
+ classes in self.composed_instances()
2011
+ additional_properties_model_instances (list): a list of the
2012
+ model instances which have the property
2013
+ additional_properties_type. This list can include self
2014
+ """
2015
+ # create composed_instances
2016
+ composed_instances = []
2017
+ allof_instances = get_allof_instances(self, model_args, constant_args)
2018
+ composed_instances.extend(allof_instances)
2019
+ oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args)
2020
+ if oneof_instance is not None:
2021
+ composed_instances.append(oneof_instance)
2022
+ anyof_instances = get_anyof_instances(self, model_args, constant_args)
2023
+ composed_instances.extend(anyof_instances)
2024
+ """
2025
+ set additional_properties_model_instances
2026
+ additional properties must be evaluated at the schema level
2027
+ so self's additional properties are most important
2028
+ If self is a composed schema with:
2029
+ - no properties defined in self
2030
+ - additionalProperties: False
2031
+ Then for object payloads every property is an additional property
2032
+ and they are not allowed, so only empty dict is allowed
2033
+
2034
+ Properties must be set on all matching schemas
2035
+ so when a property is assigned toa composed instance, it must be set on all
2036
+ composed instances regardless of additionalProperties presence
2037
+ keeping it to prevent breaking changes in v5.0.1
2038
+ TODO remove cls._additional_properties_model_instances in 6.0.0
2039
+ """
2040
+ additional_properties_model_instances = []
2041
+ if self.additional_properties_type is not None:
2042
+ additional_properties_model_instances = [self]
2043
+
2044
+ """
2045
+ no need to set properties on self in here, they will be set in __init__
2046
+ By here all composed schema oneOf/anyOf/allOf instances have their properties set using
2047
+ model_args
2048
+ """
2049
+ discarded_args = get_discarded_args(self, composed_instances, model_args)
2050
+
2051
+ # map variable names to composed_instances
2052
+ var_name_to_model_instances = {}
2053
+ for prop_name in model_args:
2054
+ if prop_name not in discarded_args:
2055
+ var_name_to_model_instances[prop_name] = [self] + composed_instances
2056
+
2057
+ return [
2058
+ composed_instances,
2059
+ var_name_to_model_instances,
2060
+ additional_properties_model_instances,
2061
+ discarded_args
2062
+ ]