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