victorycode-sdk 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. victorycode_sdk/__init__.py +260 -0
  2. victorycode_sdk/api/__init__.py +13 -0
  3. victorycode_sdk/api/authentication_api.py +285 -0
  4. victorycode_sdk/api/classification_api.py +1203 -0
  5. victorycode_sdk/api/game_recap_api.py +1395 -0
  6. victorycode_sdk/api/games_api.py +1497 -0
  7. victorycode_sdk/api/mascot_api.py +1203 -0
  8. victorycode_sdk/api/plays_events_api.py +1057 -0
  9. victorycode_sdk/api/teams_api.py +1220 -0
  10. victorycode_sdk/api/uploads_api.py +872 -0
  11. victorycode_sdk/api/venue_api.py +1203 -0
  12. victorycode_sdk/api_client.py +833 -0
  13. victorycode_sdk/api_response.py +21 -0
  14. victorycode_sdk/configuration.py +698 -0
  15. victorycode_sdk/exceptions.py +218 -0
  16. victorycode_sdk/models/__init__.py +114 -0
  17. victorycode_sdk/models/add_video_to_game_with_s3_link_dto.py +90 -0
  18. victorycode_sdk/models/address.py +96 -0
  19. victorycode_sdk/models/address_dto.py +96 -0
  20. victorycode_sdk/models/bad_request_error_response_dto.py +90 -0
  21. victorycode_sdk/models/classification.py +90 -0
  22. victorycode_sdk/models/client_create_game_with_video_url_dto.py +130 -0
  23. victorycode_sdk/models/complete_multipart_upload_dto.py +97 -0
  24. victorycode_sdk/models/complete_multipart_upload_response.py +90 -0
  25. victorycode_sdk/models/complete_multipart_upload_response_dto.py +94 -0
  26. victorycode_sdk/models/completed_part_dto.py +90 -0
  27. victorycode_sdk/models/conflict_error_response_dto.py +90 -0
  28. victorycode_sdk/models/coordinates.py +90 -0
  29. victorycode_sdk/models/coordinates_dto.py +90 -0
  30. victorycode_sdk/models/create_classification_dto.py +90 -0
  31. victorycode_sdk/models/create_mascot_dto.py +90 -0
  32. victorycode_sdk/models/create_team_dto.py +108 -0
  33. victorycode_sdk/models/create_team_response_dto.py +106 -0
  34. victorycode_sdk/models/create_venue_dto.py +102 -0
  35. victorycode_sdk/models/defense_section_dto.py +101 -0
  36. victorycode_sdk/models/defense_stats_dto.py +106 -0
  37. victorycode_sdk/models/defense_totals_dto.py +100 -0
  38. victorycode_sdk/models/delete_response_dto.py +90 -0
  39. victorycode_sdk/models/down_efficiency_dto.py +90 -0
  40. victorycode_sdk/models/fetch_team_response_dto.py +117 -0
  41. victorycode_sdk/models/fumble_section_dto.py +101 -0
  42. victorycode_sdk/models/fumble_stats_dto.py +98 -0
  43. victorycode_sdk/models/fumble_totals_dto.py +92 -0
  44. victorycode_sdk/models/game_all_play_list_item_dto.py +106 -0
  45. victorycode_sdk/models/game_box_score_meta_dto.py +104 -0
  46. victorycode_sdk/models/game_box_score_response_dto.py +98 -0
  47. victorycode_sdk/models/game_box_score_teams_dto.py +97 -0
  48. victorycode_sdk/models/game_details_response.py +108 -0
  49. victorycode_sdk/models/game_recap_scoring_summary_pro_response.py +101 -0
  50. victorycode_sdk/models/game_recap_scoring_summary_response.py +101 -0
  51. victorycode_sdk/models/game_recap_team_stats_response.py +101 -0
  52. victorycode_sdk/models/game_score_response.py +101 -0
  53. victorycode_sdk/models/game_scoring_summary_data_dto.py +104 -0
  54. victorycode_sdk/models/get_parts_presign_url_response.py +88 -0
  55. victorycode_sdk/models/get_parts_presign_url_response_dto.py +94 -0
  56. victorycode_sdk/models/initiate_multipart_upload_dto.py +92 -0
  57. victorycode_sdk/models/initiate_multipart_upload_response.py +88 -0
  58. victorycode_sdk/models/initiate_multipart_upload_response_dto.py +94 -0
  59. victorycode_sdk/models/interception_section_dto.py +101 -0
  60. victorycode_sdk/models/interception_stats_dto.py +98 -0
  61. victorycode_sdk/models/interception_totals_dto.py +92 -0
  62. victorycode_sdk/models/kicking_section_dto.py +101 -0
  63. victorycode_sdk/models/kicking_stats_dto.py +106 -0
  64. victorycode_sdk/models/kicking_totals_dto.py +100 -0
  65. victorycode_sdk/models/line_of_scrimmage_dto.py +90 -0
  66. victorycode_sdk/models/list_classification_paginated_response_dto.py +101 -0
  67. victorycode_sdk/models/list_game_all_plays_response_dto.py +103 -0
  68. victorycode_sdk/models/list_games_paginated_response_dto.py +101 -0
  69. victorycode_sdk/models/list_mascot_paginated_response_dto.py +101 -0
  70. victorycode_sdk/models/list_play_clips_response_dto.py +105 -0
  71. victorycode_sdk/models/list_team_paginated_response_dto.py +101 -0
  72. victorycode_sdk/models/list_venue_paginated_response_dto.py +101 -0
  73. victorycode_sdk/models/list_video_paginated_response_dto.py +103 -0
  74. victorycode_sdk/models/mascot.py +90 -0
  75. victorycode_sdk/models/mascot_response_dto.py +96 -0
  76. victorycode_sdk/models/not_found_error_response_dto.py +90 -0
  77. victorycode_sdk/models/offense_dto.py +92 -0
  78. victorycode_sdk/models/passing_dto.py +98 -0
  79. victorycode_sdk/models/passing_section_dto.py +101 -0
  80. victorycode_sdk/models/passing_stats_dto.py +117 -0
  81. victorycode_sdk/models/passing_totals_dto.py +111 -0
  82. victorycode_sdk/models/period_score_dto.py +94 -0
  83. victorycode_sdk/models/play_attributes_list_dto.py +106 -0
  84. victorycode_sdk/models/play_clip_list_details_dto.py +104 -0
  85. victorycode_sdk/models/play_clip_list_item_dto.py +104 -0
  86. victorycode_sdk/models/pro_scoring_play_dto.py +202 -0
  87. victorycode_sdk/models/receiving_section_dto.py +101 -0
  88. victorycode_sdk/models/receiving_stats_dto.py +104 -0
  89. victorycode_sdk/models/receiving_totals_dto.py +98 -0
  90. victorycode_sdk/models/red_zone_dto.py +90 -0
  91. victorycode_sdk/models/rushing_dto.py +92 -0
  92. victorycode_sdk/models/rushing_section_dto.py +101 -0
  93. victorycode_sdk/models/rushing_stats_dto.py +102 -0
  94. victorycode_sdk/models/rushing_totals_dto.py +96 -0
  95. victorycode_sdk/models/scoring_play_player_involved_dto.py +106 -0
  96. victorycode_sdk/models/scoring_summary_pro_team_dto.py +90 -0
  97. victorycode_sdk/models/single_classification_response_dto.py +94 -0
  98. victorycode_sdk/models/single_mascot_response_dto.py +94 -0
  99. victorycode_sdk/models/single_team_response_dto.py +94 -0
  100. victorycode_sdk/models/single_venue_response_dto.py +99 -0
  101. victorycode_sdk/models/single_video_response_dto.py +94 -0
  102. victorycode_sdk/models/team_basic_info_dto.py +96 -0
  103. victorycode_sdk/models/team_box_score_dto.py +139 -0
  104. victorycode_sdk/models/team_score_dto.py +109 -0
  105. victorycode_sdk/models/team_stats_dto.py +137 -0
  106. victorycode_sdk/models/token_response.py +92 -0
  107. victorycode_sdk/models/turnovers_dto.py +92 -0
  108. victorycode_sdk/models/unauthorized_error_response_dto.py +90 -0
  109. victorycode_sdk/models/update_classification_dto.py +90 -0
  110. victorycode_sdk/models/update_mascot_dto.py +90 -0
  111. victorycode_sdk/models/update_team_dto.py +108 -0
  112. victorycode_sdk/models/update_venue_dto.py +102 -0
  113. victorycode_sdk/models/venue.py +102 -0
  114. victorycode_sdk/models/video_list_item_dto.py +96 -0
  115. victorycode_sdk/py.typed +0 -0
  116. victorycode_sdk/rest.py +334 -0
  117. victorycode_sdk-1.0.0.dist-info/METADATA +288 -0
  118. victorycode_sdk-1.0.0.dist-info/RECORD +121 -0
  119. victorycode_sdk-1.0.0.dist-info/WHEEL +5 -0
  120. victorycode_sdk-1.0.0.dist-info/licenses/LICENSE +21 -0
  121. victorycode_sdk-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,833 @@
1
+ """
2
+ Victory Code Client API
3
+
4
+ Client APIs for Tactix partners: authenticate, upload game video, and retrieve games, plays, game recaps and team metadata.
5
+
6
+ The version of the OpenAPI document: 1.0
7
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
8
+
9
+ Do not edit the class manually.
10
+ """ # noqa: E501
11
+
12
+
13
+
14
+ import datetime
15
+ from dateutil.parser import parse
16
+ from enum import Enum
17
+ import decimal
18
+ import json
19
+ import mimetypes
20
+ import os
21
+ import re
22
+ import tempfile
23
+ import uuid
24
+
25
+ from urllib.parse import quote
26
+ from typing import Tuple, Optional, List, Dict, Union
27
+ from pydantic import SecretStr
28
+
29
+ from victorycode_sdk.configuration import Configuration
30
+ from victorycode_sdk.api_response import ApiResponse, T as ApiResponseT
31
+ import victorycode_sdk.models
32
+ from victorycode_sdk import rest
33
+ from victorycode_sdk.exceptions import (
34
+ ApiValueError,
35
+ ApiException,
36
+ BadRequestException,
37
+ UnauthorizedException,
38
+ ForbiddenException,
39
+ NotFoundException,
40
+ ServiceException
41
+ )
42
+
43
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
44
+
45
+ class ApiClient:
46
+ """Generic API client for OpenAPI client library builds.
47
+
48
+ OpenAPI generic API client. This client handles the client-
49
+ server communication, and is invariant across implementations. Specifics of
50
+ the methods and models for each application are generated from the OpenAPI
51
+ templates.
52
+
53
+ :param configuration: .Configuration object for this client
54
+ :param header_name: a header to pass when making calls to the API.
55
+ :param header_value: a header value to pass when making calls to
56
+ the API.
57
+ :param cookie: a cookie to include in the header when making calls
58
+ to the API
59
+ """
60
+
61
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
62
+ NATIVE_TYPES_MAPPING = {
63
+ 'int': int,
64
+ 'long': int, # TODO remove as only py3 is supported?
65
+ 'float': float,
66
+ 'str': str,
67
+ 'bool': bool,
68
+ 'date': datetime.date,
69
+ 'datetime': datetime.datetime,
70
+ 'decimal': decimal.Decimal,
71
+ 'UUID': uuid.UUID,
72
+ 'object': object,
73
+ }
74
+ _pool = None
75
+
76
+ def __init__(
77
+ self,
78
+ configuration=None,
79
+ header_name=None,
80
+ header_value=None,
81
+ cookie=None
82
+ ) -> None:
83
+ # use default configuration if none is provided
84
+ if configuration is None:
85
+ configuration = Configuration.get_default()
86
+ self.configuration = configuration
87
+
88
+ self.rest_client = rest.RESTClientObject(configuration)
89
+ self.default_headers = {}
90
+ if header_name is not None:
91
+ self.default_headers[header_name] = header_value
92
+ self.cookie = cookie
93
+ # Set default User-Agent.
94
+ self.user_agent = 'OpenAPI-Generator/1.0.0/python'
95
+ self.client_side_validation = configuration.client_side_validation
96
+
97
+ def __enter__(self):
98
+ return self
99
+
100
+ def __exit__(self, exc_type, exc_value, traceback):
101
+ pass
102
+
103
+ @property
104
+ def user_agent(self):
105
+ """User agent for this API client"""
106
+ return self.default_headers['User-Agent']
107
+
108
+ @user_agent.setter
109
+ def user_agent(self, value):
110
+ self.default_headers['User-Agent'] = value
111
+
112
+ def set_default_header(self, header_name, header_value):
113
+ self.default_headers[header_name] = header_value
114
+
115
+
116
+ _default = None
117
+
118
+ @classmethod
119
+ def get_default(cls):
120
+ """Return new instance of ApiClient.
121
+
122
+ This method returns newly created, based on default constructor,
123
+ object of ApiClient class or returns a copy of default
124
+ ApiClient.
125
+
126
+ :return: The ApiClient object.
127
+ """
128
+ if cls._default is None:
129
+ cls._default = ApiClient()
130
+ return cls._default
131
+
132
+ @classmethod
133
+ def set_default(cls, default):
134
+ """Set default instance of ApiClient.
135
+
136
+ It stores default ApiClient.
137
+
138
+ :param default: object of ApiClient.
139
+ """
140
+ cls._default = default
141
+
142
+ def param_serialize(
143
+ self,
144
+ method,
145
+ resource_path,
146
+ path_params=None,
147
+ query_params=None,
148
+ header_params=None,
149
+ body=None,
150
+ post_params=None,
151
+ files=None, auth_settings=None,
152
+ collection_formats=None,
153
+ _host=None,
154
+ _request_auth=None
155
+ ) -> RequestSerialized:
156
+
157
+ """Builds the HTTP request params needed by the request.
158
+ :param method: Method to call.
159
+ :param resource_path: Path to method endpoint.
160
+ :param path_params: Path parameters in the url.
161
+ :param query_params: Query parameters in the url.
162
+ :param header_params: Header parameters to be
163
+ placed in the request header.
164
+ :param body: Request body.
165
+ :param post_params dict: Request post form parameters,
166
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
167
+ :param auth_settings list: Auth Settings names for the request.
168
+ :param files dict: key -> filename, value -> filepath,
169
+ for `multipart/form-data`.
170
+ :param collection_formats: dict of collection formats for path, query,
171
+ header, and post parameters.
172
+ :param _request_auth: set to override the auth_settings for an a single
173
+ request; this effectively ignores the authentication
174
+ in the spec for a single request.
175
+ :return: tuple of form (path, http_method, query_params, header_params,
176
+ body, post_params, files)
177
+ """
178
+
179
+ config = self.configuration
180
+
181
+ # header parameters
182
+ header_params = header_params or {}
183
+ header_params.update(self.default_headers)
184
+ if self.cookie:
185
+ header_params['Cookie'] = self.cookie
186
+ if header_params:
187
+ header_params = self.sanitize_for_serialization(header_params)
188
+ header_params = dict(
189
+ self.parameters_to_tuples(header_params,collection_formats)
190
+ )
191
+
192
+ # path parameters
193
+ if path_params:
194
+ path_params = self.sanitize_for_serialization(path_params)
195
+ path_params = self.parameters_to_tuples(
196
+ path_params,
197
+ collection_formats
198
+ )
199
+ for k, v in path_params:
200
+ # specified safe chars, encode everything
201
+ resource_path = resource_path.replace(
202
+ '{%s}' % k,
203
+ quote(str(v), safe=config.safe_chars_for_path_param)
204
+ )
205
+
206
+ # post parameters
207
+ if post_params or files:
208
+ post_params = post_params if post_params else []
209
+ post_params = self.sanitize_for_serialization(post_params)
210
+ post_params = self.parameters_to_tuples(
211
+ post_params,
212
+ collection_formats
213
+ )
214
+ if files:
215
+ post_params.extend(self.files_parameters(files))
216
+
217
+ # auth setting
218
+ self.update_params_for_auth(
219
+ header_params,
220
+ query_params,
221
+ auth_settings,
222
+ resource_path,
223
+ method,
224
+ body,
225
+ request_auth=_request_auth
226
+ )
227
+
228
+ # body
229
+ if body:
230
+ body = self.sanitize_for_serialization(body)
231
+
232
+ # request url
233
+ if _host is None or self.configuration.ignore_operation_servers:
234
+ url = self.configuration.host + resource_path
235
+ else:
236
+ # use server/host defined in path or operation instead
237
+ url = _host + resource_path
238
+
239
+ # query parameters
240
+ if query_params:
241
+ query_params = self.sanitize_for_serialization(query_params)
242
+ url_query = self.parameters_to_url_query(
243
+ query_params,
244
+ collection_formats
245
+ )
246
+ url += "?" + url_query
247
+
248
+ return method, url, header_params, body, post_params
249
+
250
+ def call_api(
251
+ self,
252
+ method,
253
+ url,
254
+ header_params=None,
255
+ body=None,
256
+ post_params=None,
257
+ _request_timeout=None
258
+ ) -> rest.RESTResponse:
259
+ """Makes the HTTP request (synchronous)
260
+ :param method: Method to call.
261
+ :param url: Path to method endpoint.
262
+ :param header_params: Header parameters to be
263
+ placed in the request header.
264
+ :param body: Request body.
265
+ :param post_params dict: Request post form parameters,
266
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
267
+ :param _request_timeout: timeout setting for this request.
268
+ :return: RESTResponse
269
+ """
270
+
271
+ try:
272
+ # perform request and return response
273
+ response_data = self.rest_client.request(
274
+ method, url,
275
+ headers=header_params,
276
+ body=body, post_params=post_params,
277
+ _request_timeout=_request_timeout
278
+ )
279
+
280
+ except ApiException as e:
281
+ raise e
282
+
283
+ return response_data
284
+
285
+ def response_deserialize(
286
+ self,
287
+ response_data: rest.RESTResponse,
288
+ response_types_map: Optional[Dict[str, ApiResponseT]]=None
289
+ ) -> ApiResponse[ApiResponseT]:
290
+ """Deserializes response into an object.
291
+ :param response_data: RESTResponse object to be deserialized.
292
+ :param response_types_map: dict of response types.
293
+ :return: ApiResponse
294
+ """
295
+
296
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
297
+ assert response_data.data is not None, msg
298
+
299
+ response_type = response_types_map.get(str(response_data.status), None)
300
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
301
+ # if not found, look for '1XX', '2XX', etc.
302
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
303
+
304
+ # If the response_type has not matched (eg. did not match the previous if statements) and the default response is available, use it.
305
+ if response_type is None and str(response_data.status) not in response_types_map \
306
+ and (not isinstance(response_data.status, int) or not 100 <= response_data.status <= 599 or str(response_data.status)[0] + "XX" not in response_types_map) \
307
+ and 'default' in response_types_map:
308
+ response_type = response_types_map['default']
309
+
310
+ # deserialize response data
311
+ response_text = None
312
+ return_data = None
313
+ try:
314
+ if response_type in ("bytearray", "bytes"):
315
+ return_data = response_data.data
316
+ elif response_type == "file":
317
+ return_data = self.__deserialize_file(response_data)
318
+ elif response_type is not None:
319
+ match = None
320
+ content_type = response_data.headers.get('content-type')
321
+ if content_type is not None:
322
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
323
+ encoding = match.group(1) if match else "utf-8"
324
+ response_text = response_data.data.decode(encoding)
325
+ return_data = self.deserialize(response_text, response_type, content_type)
326
+ finally:
327
+ if not 200 <= response_data.status <= 299:
328
+ raise ApiException.from_response(
329
+ http_resp=response_data,
330
+ body=response_text,
331
+ data=return_data,
332
+ )
333
+
334
+ return ApiResponse(
335
+ status_code = response_data.status,
336
+ data = return_data,
337
+ headers = response_data.headers,
338
+ raw_data = response_data.data
339
+ )
340
+
341
+ def sanitize_for_serialization(self, obj):
342
+ """Builds a JSON POST object.
343
+
344
+ If obj is None, return None.
345
+ If obj is SecretStr, return obj.get_secret_value()
346
+ If obj is str, int, long, float, bool, return directly.
347
+ If obj is datetime.datetime, datetime.date
348
+ convert to string in iso8601 format.
349
+ If obj is decimal.Decimal return string representation.
350
+ If obj is list, sanitize each element in the list.
351
+ If obj is dict, return the dict.
352
+ If obj is OpenAPI model, return the properties dict.
353
+
354
+ :param obj: The data to serialize.
355
+ :return: The serialized form of data.
356
+ """
357
+ if obj is None:
358
+ return None
359
+ elif isinstance(obj, Enum):
360
+ return obj.value
361
+ elif isinstance(obj, SecretStr):
362
+ return obj.get_secret_value()
363
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
364
+ return obj
365
+ elif isinstance(obj, uuid.UUID):
366
+ return str(obj)
367
+ elif isinstance(obj, list):
368
+ return [
369
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
370
+ ]
371
+ elif isinstance(obj, tuple):
372
+ return tuple(
373
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
374
+ )
375
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
376
+ return obj.isoformat()
377
+ elif isinstance(obj, decimal.Decimal):
378
+ return str(obj)
379
+ elif isinstance(obj, dict):
380
+ return {
381
+ key: self.sanitize_for_serialization(val)
382
+ for key, val in obj.items()
383
+ }
384
+
385
+ # Convert model obj to dict except
386
+ # attributes `openapi_types`, `attribute_map`
387
+ # and attributes which value is not None.
388
+ # Convert attribute name to json key in
389
+ # model definition for request.
390
+ if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
391
+ obj_dict = obj.to_dict()
392
+ else:
393
+ obj_dict = obj.__dict__
394
+
395
+ return self.sanitize_for_serialization(obj_dict)
396
+
397
+
398
+ def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
399
+ """Deserializes response into an object.
400
+
401
+ :param response: RESTResponse object to be deserialized.
402
+ :param response_type: class literal for
403
+ deserialized object, or string of class name.
404
+ :param content_type: content type of response.
405
+
406
+ :return: deserialized object.
407
+ """
408
+
409
+ # fetch data from response object
410
+ if content_type is None:
411
+ try:
412
+ data = json.loads(response_text)
413
+ except ValueError:
414
+ data = response_text
415
+ elif re.match(r'^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE):
416
+ if response_text == "":
417
+ data = ""
418
+ else:
419
+ data = json.loads(response_text)
420
+ elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE):
421
+ data = response_text
422
+ else:
423
+ raise ApiException(
424
+ status=0,
425
+ reason="Unsupported content type: {0}".format(content_type)
426
+ )
427
+
428
+ return self.__deserialize(data, response_type)
429
+
430
+ def __deserialize(self, data, klass):
431
+ """Deserializes dict, list, str into an object.
432
+
433
+ :param data: dict, list or str.
434
+ :param klass: class literal, or string of class name.
435
+
436
+ :return: object.
437
+ """
438
+ if data is None:
439
+ return None
440
+
441
+ if isinstance(klass, str):
442
+ if klass.startswith('Optional['):
443
+ m = re.match(r'Optional\[(.*)]', klass)
444
+ assert m is not None, "Malformed Optional type definition"
445
+ # data is not None here, so the optionality is already resolved
446
+ return self.__deserialize(data, m.group(1))
447
+
448
+ if klass.startswith('List['):
449
+ m = re.match(r'List\[(.*)]', klass)
450
+ assert m is not None, "Malformed List type definition"
451
+ sub_kls = m.group(1)
452
+ return [self.__deserialize(sub_data, sub_kls)
453
+ for sub_data in data]
454
+
455
+ if klass.startswith('Dict['):
456
+ m = re.match(r'Dict\[([^,]*), (.*)]', klass)
457
+ assert m is not None, "Malformed Dict type definition"
458
+ sub_kls = m.group(2)
459
+ return {k: self.__deserialize(v, sub_kls)
460
+ for k, v in data.items()}
461
+
462
+ # convert str to class
463
+ if klass in self.NATIVE_TYPES_MAPPING:
464
+ klass = self.NATIVE_TYPES_MAPPING[klass]
465
+ else:
466
+ klass = getattr(victorycode_sdk.models, klass)
467
+
468
+ if klass in self.PRIMITIVE_TYPES:
469
+ return self.__deserialize_primitive(data, klass)
470
+ elif klass is object:
471
+ return self.__deserialize_object(data)
472
+ elif klass is datetime.date:
473
+ return self.__deserialize_date(data)
474
+ elif klass is datetime.datetime:
475
+ return self.__deserialize_datetime(data)
476
+ elif klass is decimal.Decimal:
477
+ return decimal.Decimal(data)
478
+ elif klass is uuid.UUID:
479
+ return uuid.UUID(data)
480
+ elif issubclass(klass, Enum):
481
+ return self.__deserialize_enum(data, klass)
482
+ else:
483
+ return self.__deserialize_model(data, klass)
484
+
485
+ def parameters_to_tuples(self, params, collection_formats):
486
+ """Get parameters as list of tuples, formatting collections.
487
+
488
+ :param params: Parameters as dict or list of two-tuples
489
+ :param dict collection_formats: Parameter collection formats
490
+ :return: Parameters as list of tuples, collections formatted
491
+ """
492
+ new_params: List[Tuple[str, str]] = []
493
+ if collection_formats is None:
494
+ collection_formats = {}
495
+ for k, v in params.items() if isinstance(params, dict) else params:
496
+ if isinstance(v, bool):
497
+ v = str(v).lower()
498
+ if k in collection_formats:
499
+ collection_format = collection_formats[k]
500
+ if collection_format == 'multi':
501
+ new_params.extend(
502
+ (k, str(value).lower() if isinstance(value, bool) else value)
503
+ for value in v
504
+ )
505
+ else:
506
+ if collection_format == 'ssv':
507
+ delimiter = ' '
508
+ elif collection_format == 'tsv':
509
+ delimiter = '\t'
510
+ elif collection_format == 'pipes':
511
+ delimiter = '|'
512
+ else: # csv is the default
513
+ delimiter = ','
514
+ new_params.append(
515
+ (k, delimiter.join(
516
+ str(value).lower() if isinstance(value, bool) else str(value)
517
+ for value in v)))
518
+ else:
519
+ new_params.append((k, v))
520
+ return new_params
521
+
522
+ def parameters_to_url_query(self, params, collection_formats):
523
+ """Get parameters as list of tuples, formatting collections.
524
+
525
+ :param params: Parameters as dict or list of two-tuples
526
+ :param dict collection_formats: Parameter collection formats
527
+ :return: URL query string (e.g. a=Hello%20World&b=123)
528
+ """
529
+ new_params: List[Tuple[str, str]] = []
530
+ if collection_formats is None:
531
+ collection_formats = {}
532
+ for k, v in params.items() if isinstance(params, dict) else params:
533
+ if isinstance(v, bool):
534
+ v = str(v).lower()
535
+ if isinstance(v, (int, float)):
536
+ v = str(v)
537
+ if isinstance(v, dict):
538
+ v = json.dumps(v)
539
+
540
+ if k in collection_formats:
541
+ collection_format = collection_formats[k]
542
+ if collection_format == 'multi':
543
+ new_params.extend(
544
+ (k, quote(str(value).lower() if isinstance(value, bool) else str(value)))
545
+ for value in v
546
+ )
547
+ else:
548
+ if collection_format == 'ssv':
549
+ delimiter = ' '
550
+ elif collection_format == 'tsv':
551
+ delimiter = '\t'
552
+ elif collection_format == 'pipes':
553
+ delimiter = '|'
554
+ else: # csv is the default
555
+ delimiter = ','
556
+ new_params.append(
557
+ (k, delimiter.join(
558
+ quote(str(value).lower() if isinstance(value, bool) else str(value))
559
+ for value in v))
560
+ )
561
+ else:
562
+ new_params.append((k, quote(str(v))))
563
+
564
+ return "&".join(["=".join(map(str, item)) for item in new_params])
565
+
566
+ def files_parameters(
567
+ self,
568
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
569
+ ):
570
+ """Builds form parameters.
571
+
572
+ :param files: File parameters.
573
+ :return: Form parameters with files.
574
+ """
575
+ params = []
576
+ for k, v in files.items():
577
+ if isinstance(v, str):
578
+ with open(v, 'rb') as f:
579
+ filename = os.path.basename(f.name)
580
+ filedata = f.read()
581
+ elif isinstance(v, bytes):
582
+ filename = k
583
+ filedata = v
584
+ elif isinstance(v, tuple):
585
+ filename, filedata = v
586
+ elif isinstance(v, list):
587
+ for file_param in v:
588
+ params.extend(self.files_parameters({k: file_param}))
589
+ continue
590
+ else:
591
+ raise ValueError("Unsupported file value")
592
+ mimetype = (
593
+ mimetypes.guess_type(filename)[0]
594
+ or 'application/octet-stream'
595
+ )
596
+ params.append(
597
+ tuple([k, tuple([filename, filedata, mimetype])])
598
+ )
599
+ return params
600
+
601
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
602
+ """Returns `Accept` based on an array of accepts provided.
603
+
604
+ :param accepts: List of headers.
605
+ :return: Accept (e.g. application/json).
606
+ """
607
+ if not accepts:
608
+ return None
609
+
610
+ for accept in accepts:
611
+ if re.search('json', accept, re.IGNORECASE):
612
+ return accept
613
+
614
+ return accepts[0]
615
+
616
+ def select_header_content_type(self, content_types):
617
+ """Returns `Content-Type` based on an array of content_types provided.
618
+
619
+ :param content_types: List of content-types.
620
+ :return: Content-Type (e.g. application/json).
621
+ """
622
+ if not content_types:
623
+ return None
624
+
625
+ for content_type in content_types:
626
+ if re.search('json', content_type, re.IGNORECASE):
627
+ return content_type
628
+
629
+ return content_types[0]
630
+
631
+ def update_params_for_auth(
632
+ self,
633
+ headers,
634
+ queries,
635
+ auth_settings,
636
+ resource_path,
637
+ method,
638
+ body,
639
+ request_auth=None
640
+ ) -> None:
641
+ """Updates header and query params based on authentication setting.
642
+
643
+ :param headers: Header parameters dict to be updated.
644
+ :param queries: Query parameters tuple list to be updated.
645
+ :param auth_settings: Authentication setting identifiers list.
646
+ :resource_path: A string representation of the HTTP request resource path.
647
+ :method: A string representation of the HTTP request method.
648
+ :body: A object representing the body of the HTTP request.
649
+ The object type is the return value of sanitize_for_serialization().
650
+ :param request_auth: if set, the provided settings will
651
+ override the token in the configuration.
652
+ """
653
+ if not auth_settings:
654
+ return
655
+
656
+ if request_auth:
657
+ self._apply_auth_params(
658
+ headers,
659
+ queries,
660
+ resource_path,
661
+ method,
662
+ body,
663
+ request_auth
664
+ )
665
+ else:
666
+ for auth in auth_settings:
667
+ auth_setting = self.configuration.auth_settings().get(auth)
668
+ if auth_setting:
669
+ self._apply_auth_params(
670
+ headers,
671
+ queries,
672
+ resource_path,
673
+ method,
674
+ body,
675
+ auth_setting
676
+ )
677
+
678
+ def _apply_auth_params(
679
+ self,
680
+ headers,
681
+ queries,
682
+ resource_path,
683
+ method,
684
+ body,
685
+ auth_setting
686
+ ) -> None:
687
+ """Updates the request parameters based on a single auth_setting
688
+
689
+ :param headers: Header parameters dict to be updated.
690
+ :param queries: Query parameters tuple list to be updated.
691
+ :resource_path: A string representation of the HTTP request resource path.
692
+ :method: A string representation of the HTTP request method.
693
+ :body: A object representing the body of the HTTP request.
694
+ The object type is the return value of sanitize_for_serialization().
695
+ :param auth_setting: auth settings for the endpoint
696
+ """
697
+ if auth_setting['in'] == 'cookie':
698
+ if not 'Cookie' in headers:
699
+ headers['Cookie'] = ""
700
+ else:
701
+ headers['Cookie'] += "; "
702
+ # Account for cookie value containing spaces and special characters, excluding base64 delimiters
703
+ cookie_value = quote(str(auth_setting['value']), safe="!#$%&'()*+-./:<=>?@[]^_`{|}~%+/=")
704
+ headers['Cookie'] += f"{auth_setting['key']}={cookie_value}"
705
+ elif auth_setting['in'] == 'header':
706
+ if auth_setting['type'] != 'http-signature':
707
+ headers[auth_setting['key']] = auth_setting['value']
708
+ elif auth_setting['in'] == 'query':
709
+ queries.append((auth_setting['key'], auth_setting['value']))
710
+ else:
711
+ raise ApiValueError(
712
+ 'Authentication token must be in `query` or `header`'
713
+ )
714
+
715
+ def __deserialize_file(self, response):
716
+ """Deserializes body to file
717
+
718
+ Saves response body into a file in a temporary folder,
719
+ using the filename from the `Content-Disposition` header if provided.
720
+
721
+ handle file downloading
722
+ save response body into a tmp file and return the instance
723
+
724
+ :param response: RESTResponse.
725
+ :return: file path.
726
+ """
727
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
728
+ os.close(fd)
729
+ os.remove(path)
730
+
731
+ content_disposition = response.headers.get("Content-Disposition")
732
+ if content_disposition:
733
+ m = re.search(
734
+ r'filename=[\'"]?([^\'"\s]+)[\'"]?',
735
+ content_disposition
736
+ )
737
+ assert m is not None, "Unexpected 'content-disposition' header value"
738
+ filename = os.path.basename(m.group(1)) # Strip any directory traversal
739
+ if filename in ("", ".", ".."): # fall back to tmp filename
740
+ filename = os.path.basename(path)
741
+ path = os.path.join(os.path.dirname(path), filename)
742
+
743
+ with open(path, "wb") as f:
744
+ f.write(response.data)
745
+
746
+ return path
747
+
748
+ def __deserialize_primitive(self, data, klass):
749
+ """Deserializes string to primitive type.
750
+
751
+ :param data: str.
752
+ :param klass: class literal.
753
+
754
+ :return: int, long, float, str, bool.
755
+ """
756
+ try:
757
+ return klass(data)
758
+ except UnicodeEncodeError:
759
+ return str(data)
760
+ except TypeError:
761
+ return data
762
+
763
+ def __deserialize_object(self, value):
764
+ """Return an original value.
765
+
766
+ :return: object.
767
+ """
768
+ return value
769
+
770
+ def __deserialize_date(self, string):
771
+ """Deserializes string to date.
772
+
773
+ :param string: str.
774
+ :return: date.
775
+ """
776
+ try:
777
+ return parse(string).date()
778
+ except ImportError:
779
+ return string
780
+ except ValueError:
781
+ raise rest.ApiException(
782
+ status=0,
783
+ reason="Failed to parse `{0}` as date object".format(string)
784
+ )
785
+
786
+ def __deserialize_datetime(self, string):
787
+ """Deserializes string to datetime.
788
+
789
+ The string should be in iso8601 datetime format.
790
+
791
+ :param string: str.
792
+ :return: datetime.
793
+ """
794
+ try:
795
+ return parse(string)
796
+ except ImportError:
797
+ return string
798
+ except ValueError:
799
+ raise rest.ApiException(
800
+ status=0,
801
+ reason=(
802
+ "Failed to parse `{0}` as datetime object"
803
+ .format(string)
804
+ )
805
+ )
806
+
807
+ def __deserialize_enum(self, data, klass):
808
+ """Deserializes primitive type to enum.
809
+
810
+ :param data: primitive type.
811
+ :param klass: class literal.
812
+ :return: enum value.
813
+ """
814
+ try:
815
+ return klass(data)
816
+ except ValueError:
817
+ raise rest.ApiException(
818
+ status=0,
819
+ reason=(
820
+ "Failed to parse `{0}` as `{1}`"
821
+ .format(data, klass)
822
+ )
823
+ )
824
+
825
+ def __deserialize_model(self, data, klass):
826
+ """Deserializes list or dict to model.
827
+
828
+ :param data: dict, list.
829
+ :param klass: class literal.
830
+ :return: model object.
831
+ """
832
+
833
+ return klass.from_dict(data)