development-framework-cli 1.7.3__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 (71) hide show
  1. development_framework_cli-1.7.3.dist-info/METADATA +141 -0
  2. development_framework_cli-1.7.3.dist-info/RECORD +71 -0
  3. development_framework_cli-1.7.3.dist-info/WHEEL +4 -0
  4. development_framework_cli-1.7.3.dist-info/entry_points.txt +2 -0
  5. development_framework_cli-1.7.3.dist-info/licenses/LICENSE +21 -0
  6. dm_cli/__init__.py +1 -0
  7. dm_cli/cli.py +180 -0
  8. dm_cli/command_group/__init__.py +0 -0
  9. dm_cli/command_group/data_source.py +176 -0
  10. dm_cli/command_group/entities.py +116 -0
  11. dm_cli/dmss.py +104 -0
  12. dm_cli/dmss_api/__init__.py +27 -0
  13. dm_cli/dmss_api/api/__init__.py +3 -0
  14. dm_cli/dmss_api/api/access_control_api.py +349 -0
  15. dm_cli/dmss_api/api/attribute_api.py +175 -0
  16. dm_cli/dmss_api/api/blob_api.py +344 -0
  17. dm_cli/dmss_api/api/blueprint_api.py +326 -0
  18. dm_cli/dmss_api/api/datasource_api.py +448 -0
  19. dm_cli/dmss_api/api/default_api.py +4439 -0
  20. dm_cli/dmss_api/api/document_api.py +922 -0
  21. dm_cli/dmss_api/api/entity_api.py +464 -0
  22. dm_cli/dmss_api/api/export_api.py +313 -0
  23. dm_cli/dmss_api/api/file_api.py +197 -0
  24. dm_cli/dmss_api/api/health_check_api.py +160 -0
  25. dm_cli/dmss_api/api/lookup_table_api.py +323 -0
  26. dm_cli/dmss_api/api/meta_api.py +185 -0
  27. dm_cli/dmss_api/api/personal_access_token_api.py +433 -0
  28. dm_cli/dmss_api/api/reference_api.py +174 -0
  29. dm_cli/dmss_api/api/search_api.py +183 -0
  30. dm_cli/dmss_api/api/whoami_api.py +163 -0
  31. dm_cli/dmss_api/api_client.py +896 -0
  32. dm_cli/dmss_api/apis/__init__.py +32 -0
  33. dm_cli/dmss_api/configuration.py +482 -0
  34. dm_cli/dmss_api/exceptions.py +158 -0
  35. dm_cli/dmss_api/model/__init__.py +5 -0
  36. dm_cli/dmss_api/model/access_control_list.py +287 -0
  37. dm_cli/dmss_api/model/access_level.py +290 -0
  38. dm_cli/dmss_api/model/acl.py +287 -0
  39. dm_cli/dmss_api/model/data_source_information.py +282 -0
  40. dm_cli/dmss_api/model/data_source_request.py +281 -0
  41. dm_cli/dmss_api/model/dependency.py +294 -0
  42. dm_cli/dmss_api/model/entity.py +275 -0
  43. dm_cli/dmss_api/model/error_response.py +278 -0
  44. dm_cli/dmss_api/model/export_meta_response.py +277 -0
  45. dm_cli/dmss_api/model/get_blueprint_response.py +280 -0
  46. dm_cli/dmss_api/model/lookup.py +283 -0
  47. dm_cli/dmss_api/model/pat_data.py +299 -0
  48. dm_cli/dmss_api/model/recipe.py +311 -0
  49. dm_cli/dmss_api/model/recipe_attribute.py +304 -0
  50. dm_cli/dmss_api/model/reference.py +280 -0
  51. dm_cli/dmss_api/model/reference_entity.py +288 -0
  52. dm_cli/dmss_api/model/repository.py +317 -0
  53. dm_cli/dmss_api/model/repository_type.py +290 -0
  54. dm_cli/dmss_api/model/storage_attribute.py +295 -0
  55. dm_cli/dmss_api/model/storage_data_types.py +292 -0
  56. dm_cli/dmss_api/model/storage_recipe.py +293 -0
  57. dm_cli/dmss_api/model_utils.py +2057 -0
  58. dm_cli/dmss_api/models/__init__.py +29 -0
  59. dm_cli/dmss_api/rest.py +358 -0
  60. dm_cli/domain.py +166 -0
  61. dm_cli/enums.py +48 -0
  62. dm_cli/import_entity.py +128 -0
  63. dm_cli/import_package.py +173 -0
  64. dm_cli/package_tree_from_zip.py +120 -0
  65. dm_cli/state.py +12 -0
  66. dm_cli/utils/__init__.py +0 -0
  67. dm_cli/utils/file_structure.py +31 -0
  68. dm_cli/utils/reference.py +129 -0
  69. dm_cli/utils/resolve_local_ids.py +142 -0
  70. dm_cli/utils/utils.py +161 -0
  71. dm_cli/utils/zip.py +70 -0
@@ -0,0 +1,896 @@
1
+ """
2
+ Data Modelling Storage Service
3
+
4
+ API for basic data modelling interaction # noqa: E501
5
+
6
+ The version of the OpenAPI document: 1.3.0
7
+ Generated by: https://openapi-generator.tech
8
+ """
9
+
10
+
11
+ import atexit
12
+ import io
13
+ import json
14
+ import mimetypes
15
+ import os
16
+ import re
17
+ import typing
18
+ from multiprocessing.pool import ThreadPool
19
+ from urllib.parse import quote
20
+
21
+ from urllib3.fields import RequestField
22
+
23
+ from dm_cli.dmss_api import rest
24
+ from dm_cli.dmss_api.configuration import Configuration
25
+ from dm_cli.dmss_api.exceptions import ApiException, ApiTypeError, ApiValueError
26
+ from dm_cli.dmss_api.model_utils import (
27
+ ModelComposed,
28
+ ModelNormal,
29
+ ModelSimple,
30
+ check_allowed_values,
31
+ check_validations,
32
+ date,
33
+ datetime,
34
+ deserialize_file,
35
+ file_type,
36
+ model_to_dict,
37
+ none_type,
38
+ validate_and_convert_types,
39
+ )
40
+
41
+
42
+ class ApiClient(object):
43
+ """Generic API client for OpenAPI client library builds.
44
+
45
+ OpenAPI generic API client. This client handles the client-
46
+ server communication, and is invariant across implementations. Specifics of
47
+ the methods and models for each application are generated from the OpenAPI
48
+ templates.
49
+
50
+ NOTE: This class is auto generated by OpenAPI Generator.
51
+ Ref: https://openapi-generator.tech
52
+ Do not edit the class manually.
53
+
54
+ :param configuration: .Configuration object for this client
55
+ :param header_name: a header to pass when making calls to the API.
56
+ :param header_value: a header value to pass when making calls to
57
+ the API.
58
+ :param cookie: a cookie to include in the header when making calls
59
+ to the API
60
+ :param pool_threads: The number of threads to use for async requests
61
+ to the API. More threads means more concurrent API requests.
62
+ """
63
+
64
+ _pool = None
65
+
66
+ def __init__(self, configuration=None, header_name=None, header_value=None,
67
+ cookie=None, pool_threads=1):
68
+ if configuration is None:
69
+ configuration = Configuration.get_default_copy()
70
+ self.configuration = configuration
71
+ self.pool_threads = pool_threads
72
+
73
+ self.rest_client = rest.RESTClientObject(configuration)
74
+ self.default_headers = {}
75
+ if header_name is not None:
76
+ self.default_headers[header_name] = header_value
77
+ self.cookie = cookie
78
+ # Set default User-Agent.
79
+ self.user_agent = 'OpenAPI-Generator/1.0.0/python'
80
+
81
+ def __enter__(self):
82
+ return self
83
+
84
+ def __exit__(self, exc_type, exc_value, traceback):
85
+ self.close()
86
+
87
+ def close(self):
88
+ if self._pool:
89
+ self._pool.close()
90
+ self._pool.join()
91
+ self._pool = None
92
+ if hasattr(atexit, 'unregister'):
93
+ atexit.unregister(self.close)
94
+
95
+ @property
96
+ def pool(self):
97
+ """Create thread pool on first request
98
+ avoids instantiating unused threadpool for blocking clients.
99
+ """
100
+ if self._pool is None:
101
+ atexit.register(self.close)
102
+ self._pool = ThreadPool(self.pool_threads)
103
+ return self._pool
104
+
105
+ @property
106
+ def user_agent(self):
107
+ """User agent for this API client"""
108
+ return self.default_headers['User-Agent']
109
+
110
+ @user_agent.setter
111
+ def user_agent(self, value):
112
+ self.default_headers['User-Agent'] = value
113
+
114
+ def set_default_header(self, header_name, header_value):
115
+ self.default_headers[header_name] = header_value
116
+
117
+ def __call_api(
118
+ self,
119
+ resource_path: str,
120
+ method: str,
121
+ path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
122
+ query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
123
+ header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
124
+ body: typing.Optional[typing.Any] = None,
125
+ post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
126
+ files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
127
+ response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
128
+ auth_settings: typing.Optional[typing.List[str]] = None,
129
+ _return_http_data_only: typing.Optional[bool] = None,
130
+ collection_formats: typing.Optional[typing.Dict[str, str]] = None,
131
+ _preload_content: bool = True,
132
+ _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
133
+ _host: typing.Optional[str] = None,
134
+ _check_type: typing.Optional[bool] = None,
135
+ _content_type: typing.Optional[str] = None,
136
+ _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None
137
+ ):
138
+
139
+ config = self.configuration
140
+
141
+ # header parameters
142
+ header_params = header_params or {}
143
+ header_params.update(self.default_headers)
144
+ if self.cookie:
145
+ header_params['Cookie'] = self.cookie
146
+ if header_params:
147
+ header_params = self.sanitize_for_serialization(header_params)
148
+ header_params = dict(self.parameters_to_tuples(header_params,
149
+ collection_formats))
150
+
151
+ # path parameters
152
+ if path_params:
153
+ path_params = self.sanitize_for_serialization(path_params)
154
+ path_params = self.parameters_to_tuples(path_params,
155
+ collection_formats)
156
+ for k, v in path_params:
157
+ # specified safe chars, encode everything
158
+ resource_path = resource_path.replace(
159
+ '{%s}' % k,
160
+ quote(str(v), safe=config.safe_chars_for_path_param)
161
+ )
162
+
163
+ # query parameters
164
+ if query_params:
165
+ query_params = self.sanitize_for_serialization(query_params)
166
+ query_params = self.parameters_to_tuples(query_params,
167
+ collection_formats)
168
+
169
+ # post parameters
170
+ if post_params or files:
171
+ post_params = post_params if post_params else []
172
+ post_params = self.sanitize_for_serialization(post_params)
173
+ post_params = self.parameters_to_tuples(post_params,
174
+ collection_formats)
175
+ post_params.extend(self.files_parameters(files))
176
+ if header_params['Content-Type'].startswith("multipart"):
177
+ post_params = self.parameters_to_multipart(post_params,
178
+ (dict))
179
+
180
+ # body
181
+ if body:
182
+ body = self.sanitize_for_serialization(body)
183
+
184
+ # auth setting
185
+ self.update_params_for_auth(header_params, query_params,
186
+ auth_settings, resource_path, method, body,
187
+ request_auths=_request_auths)
188
+
189
+ # request url
190
+ if _host is None:
191
+ url = self.configuration.host + resource_path
192
+ else:
193
+ # use server/host defined in path or operation instead
194
+ url = _host + resource_path
195
+
196
+ try:
197
+ # perform request and return response
198
+ response_data = self.request(
199
+ method, url, query_params=query_params, headers=header_params,
200
+ post_params=post_params, body=body,
201
+ _preload_content=_preload_content,
202
+ _request_timeout=_request_timeout)
203
+ except ApiException as e:
204
+ e.body = e.body.decode('utf-8')
205
+ raise e
206
+
207
+ self.last_response = response_data
208
+
209
+ return_data = response_data
210
+
211
+ if not _preload_content:
212
+ return (return_data)
213
+ return return_data
214
+
215
+ # deserialize response data
216
+ if response_type:
217
+ if response_type != (file_type,):
218
+ encoding = "utf-8"
219
+ content_type = response_data.getheader('content-type')
220
+ if content_type is not None:
221
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
222
+ if match:
223
+ encoding = match.group(1)
224
+ response_data.data = response_data.data.decode(encoding)
225
+
226
+ return_data = self.deserialize(
227
+ response_data,
228
+ response_type,
229
+ _check_type
230
+ )
231
+ else:
232
+ return_data = None
233
+
234
+ if _return_http_data_only:
235
+ return (return_data)
236
+ else:
237
+ return (return_data, response_data.status,
238
+ response_data.getheaders())
239
+
240
+ def parameters_to_multipart(self, params, collection_types):
241
+ """Get parameters as list of tuples, formatting as json if value is collection_types
242
+
243
+ :param params: Parameters as list of two-tuples
244
+ :param dict collection_types: Parameter collection types
245
+ :return: Parameters as list of tuple or urllib3.fields.RequestField
246
+ """
247
+ new_params = []
248
+ if collection_types is None:
249
+ collection_types = (dict)
250
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
251
+ if isinstance(
252
+ v, collection_types): # v is instance of collection_type, formatting as application/json
253
+ v = json.dumps(v, ensure_ascii=False).encode("utf-8")
254
+ field = RequestField(k, v)
255
+ field.make_multipart(content_type="application/json; charset=utf-8")
256
+ new_params.append(field)
257
+ else:
258
+ new_params.append((k, v))
259
+ return new_params
260
+
261
+ @classmethod
262
+ def sanitize_for_serialization(cls, obj):
263
+ """Prepares data for transmission before it is sent with the rest client
264
+ If obj is None, return None.
265
+ If obj is str, int, long, float, bool, return directly.
266
+ If obj is datetime.datetime, datetime.date
267
+ convert to string in iso8601 format.
268
+ If obj is list, sanitize each element in the list.
269
+ If obj is dict, return the dict.
270
+ If obj is OpenAPI model, return the properties dict.
271
+ If obj is io.IOBase, return the bytes
272
+ :param obj: The data to serialize.
273
+ :return: The serialized form of data.
274
+ """
275
+ if isinstance(obj, (ModelNormal, ModelComposed)):
276
+ return {
277
+ key: cls.sanitize_for_serialization(val) for key,
278
+ val in model_to_dict(
279
+ obj,
280
+ serialize=True).items()}
281
+ elif isinstance(obj, io.IOBase):
282
+ return cls.get_file_data_and_close_file(obj)
283
+ elif isinstance(obj, (str, int, float, none_type, bool)):
284
+ return obj
285
+ elif isinstance(obj, (datetime, date)):
286
+ return obj.isoformat()
287
+ elif isinstance(obj, ModelSimple):
288
+ return cls.sanitize_for_serialization(obj.value)
289
+ elif isinstance(obj, (list, tuple)):
290
+ return [cls.sanitize_for_serialization(item) for item in obj]
291
+ if isinstance(obj, dict):
292
+ return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
293
+ raise ApiValueError(
294
+ 'Unable to prepare type {} for serialization'.format(
295
+ obj.__class__.__name__))
296
+
297
+ def deserialize(self, response, response_type, _check_type):
298
+ """Deserializes response into an object.
299
+
300
+ :param response: RESTResponse object to be deserialized.
301
+ :param response_type: For the response, a tuple containing:
302
+ valid classes
303
+ a list containing valid classes (for list schemas)
304
+ a dict containing a tuple of valid classes as the value
305
+ Example values:
306
+ (str,)
307
+ (Pet,)
308
+ (float, none_type)
309
+ ([int, none_type],)
310
+ ({str: (bool, str, int, float, date, datetime, str, none_type)},)
311
+ :param _check_type: boolean, whether to check the types of the data
312
+ received from the server
313
+ :type _check_type: bool
314
+
315
+ :return: deserialized object.
316
+ """
317
+ # handle file downloading
318
+ # save response body into a tmp file and return the instance
319
+ if response_type == (file_type,):
320
+ content_disposition = response.getheader("Content-Disposition")
321
+ return deserialize_file(response.data, self.configuration,
322
+ content_disposition=content_disposition)
323
+
324
+ # fetch data from response object
325
+ try:
326
+ received_data = json.loads(response.data)
327
+ except ValueError:
328
+ received_data = response.data
329
+
330
+ # store our data under the key of 'received_data' so users have some
331
+ # context if they are deserializing a string and the data type is wrong
332
+ deserialized_data = validate_and_convert_types(
333
+ received_data,
334
+ response_type,
335
+ ['received_data'],
336
+ True,
337
+ _check_type,
338
+ configuration=self.configuration
339
+ )
340
+ return deserialized_data
341
+
342
+ def call_api(
343
+ self,
344
+ resource_path: str,
345
+ method: str,
346
+ path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
347
+ query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
348
+ header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
349
+ body: typing.Optional[typing.Any] = None,
350
+ post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
351
+ files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
352
+ response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
353
+ auth_settings: typing.Optional[typing.List[str]] = None,
354
+ async_req: typing.Optional[bool] = None,
355
+ _return_http_data_only: typing.Optional[bool] = None,
356
+ collection_formats: typing.Optional[typing.Dict[str, str]] = None,
357
+ _preload_content: bool = True,
358
+ _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
359
+ _host: typing.Optional[str] = None,
360
+ _check_type: typing.Optional[bool] = None,
361
+ _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None
362
+ ):
363
+ """Makes the HTTP request (synchronous) and returns deserialized data.
364
+
365
+ To make an async_req request, set the async_req parameter.
366
+
367
+ :param resource_path: Path to method endpoint.
368
+ :param method: Method to call.
369
+ :param path_params: Path parameters in the url.
370
+ :param query_params: Query parameters in the url.
371
+ :param header_params: Header parameters to be
372
+ placed in the request header.
373
+ :param body: Request body.
374
+ :param post_params dict: Request post form parameters,
375
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
376
+ :param auth_settings list: Auth Settings names for the request.
377
+ :param response_type: For the response, a tuple containing:
378
+ valid classes
379
+ a list containing valid classes (for list schemas)
380
+ a dict containing a tuple of valid classes as the value
381
+ Example values:
382
+ (str,)
383
+ (Pet,)
384
+ (float, none_type)
385
+ ([int, none_type],)
386
+ ({str: (bool, str, int, float, date, datetime, str, none_type)},)
387
+ :param files: key -> field name, value -> a list of open file
388
+ objects for `multipart/form-data`.
389
+ :type files: dict
390
+ :param async_req bool: execute request asynchronously
391
+ :type async_req: bool, optional
392
+ :param _return_http_data_only: response data without head status code
393
+ and headers
394
+ :type _return_http_data_only: bool, optional
395
+ :param collection_formats: dict of collection formats for path, query,
396
+ header, and post parameters.
397
+ :type collection_formats: dict, optional
398
+ :param _preload_content: if False, the urllib3.HTTPResponse object will
399
+ be returned without reading/decoding response
400
+ data. Default is True.
401
+ :type _preload_content: bool, optional
402
+ :param _request_timeout: timeout setting for this request. If one
403
+ number provided, it will be total request
404
+ timeout. It can also be a pair (tuple) of
405
+ (connection, read) timeouts.
406
+ :param _check_type: boolean describing if the data back from the server
407
+ should have its type checked.
408
+ :type _check_type: bool, optional
409
+ :param _request_auths: set to override the auth_settings for an a single
410
+ request; this effectively ignores the authentication
411
+ in the spec for a single request.
412
+ :type _request_auths: list, optional
413
+ :return:
414
+ If async_req parameter is True,
415
+ the request will be called asynchronously.
416
+ The method will return the request thread.
417
+ If parameter async_req is False or missing,
418
+ then the method will return the response directly.
419
+ """
420
+ if not async_req:
421
+ return self.__call_api(resource_path, method,
422
+ path_params, query_params, header_params,
423
+ body, post_params, files,
424
+ response_type, auth_settings,
425
+ _return_http_data_only, collection_formats,
426
+ _preload_content, _request_timeout, _host,
427
+ _check_type, _request_auths=_request_auths)
428
+
429
+ return self.pool.apply_async(self.__call_api, (resource_path,
430
+ method, path_params,
431
+ query_params,
432
+ header_params, body,
433
+ post_params, files,
434
+ response_type,
435
+ auth_settings,
436
+ _return_http_data_only,
437
+ collection_formats,
438
+ _preload_content,
439
+ _request_timeout,
440
+ _host, _check_type, None, _request_auths))
441
+
442
+ def request(self, method, url, query_params=None, headers=None,
443
+ post_params=None, body=None, _preload_content=True,
444
+ _request_timeout=None):
445
+ """Makes the HTTP request using RESTClient."""
446
+ if method == "GET":
447
+ return self.rest_client.GET(url,
448
+ query_params=query_params,
449
+ _preload_content=_preload_content,
450
+ _request_timeout=_request_timeout,
451
+ headers=headers)
452
+ elif method == "HEAD":
453
+ return self.rest_client.HEAD(url,
454
+ query_params=query_params,
455
+ _preload_content=_preload_content,
456
+ _request_timeout=_request_timeout,
457
+ headers=headers)
458
+ elif method == "OPTIONS":
459
+ return self.rest_client.OPTIONS(url,
460
+ query_params=query_params,
461
+ headers=headers,
462
+ post_params=post_params,
463
+ _preload_content=_preload_content,
464
+ _request_timeout=_request_timeout,
465
+ body=body)
466
+ elif method == "POST":
467
+ return self.rest_client.POST(url,
468
+ query_params=query_params,
469
+ headers=headers,
470
+ post_params=post_params,
471
+ _preload_content=_preload_content,
472
+ _request_timeout=_request_timeout,
473
+ body=body)
474
+ elif method == "PUT":
475
+ return self.rest_client.PUT(url,
476
+ query_params=query_params,
477
+ headers=headers,
478
+ post_params=post_params,
479
+ _preload_content=_preload_content,
480
+ _request_timeout=_request_timeout,
481
+ body=body)
482
+ elif method == "PATCH":
483
+ return self.rest_client.PATCH(url,
484
+ query_params=query_params,
485
+ headers=headers,
486
+ post_params=post_params,
487
+ _preload_content=_preload_content,
488
+ _request_timeout=_request_timeout,
489
+ body=body)
490
+ elif method == "DELETE":
491
+ return self.rest_client.DELETE(url,
492
+ query_params=query_params,
493
+ headers=headers,
494
+ _preload_content=_preload_content,
495
+ _request_timeout=_request_timeout,
496
+ body=body)
497
+ else:
498
+ raise ApiValueError(
499
+ "http method must be `GET`, `HEAD`, `OPTIONS`,"
500
+ " `POST`, `PATCH`, `PUT` or `DELETE`."
501
+ )
502
+
503
+ def parameters_to_tuples(self, params, collection_formats):
504
+ """Get parameters as list of tuples, formatting collections.
505
+
506
+ :param params: Parameters as dict or list of two-tuples
507
+ :param dict collection_formats: Parameter collection formats
508
+ :return: Parameters as list of tuples, collections formatted
509
+ """
510
+ new_params = []
511
+ if collection_formats is None:
512
+ collection_formats = {}
513
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
514
+ if k in collection_formats:
515
+ collection_format = collection_formats[k]
516
+ if collection_format == 'multi':
517
+ new_params.extend((k, value) for value in v)
518
+ else:
519
+ if collection_format == 'ssv':
520
+ delimiter = ' '
521
+ elif collection_format == 'tsv':
522
+ delimiter = '\t'
523
+ elif collection_format == 'pipes':
524
+ delimiter = '|'
525
+ else: # csv is the default
526
+ delimiter = ','
527
+ new_params.append(
528
+ (k, delimiter.join(str(value) for value in v)))
529
+ else:
530
+ new_params.append((k, v))
531
+ return new_params
532
+
533
+ @staticmethod
534
+ def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes:
535
+ file_data = file_instance.read()
536
+ file_instance.close()
537
+ return file_data
538
+
539
+ def files_parameters(self,
540
+ files: typing.Optional[typing.Dict[str,
541
+ typing.List[io.IOBase]]] = None):
542
+ """Builds form parameters.
543
+
544
+ :param files: None or a dict with key=param_name and
545
+ value is a list of open file objects
546
+ :return: List of tuples of form parameters with file data
547
+ """
548
+ if files is None:
549
+ return []
550
+
551
+ params = []
552
+ for param_name, file_instances in files.items():
553
+ if file_instances is None:
554
+ # if the file field is nullable, skip None values
555
+ continue
556
+ for file_instance in file_instances:
557
+ if file_instance is None:
558
+ # if the file field is nullable, skip None values
559
+ continue
560
+ if file_instance.closed is True:
561
+ raise ApiValueError(
562
+ "Cannot read a closed file. The passed in file_type "
563
+ "for %s must be open." % param_name
564
+ )
565
+ filename = os.path.basename(file_instance.name)
566
+ filedata = self.get_file_data_and_close_file(file_instance)
567
+ mimetype = (mimetypes.guess_type(filename)[0] or
568
+ 'application/octet-stream')
569
+ params.append(
570
+ tuple([param_name, tuple([filename, filedata, mimetype])]))
571
+
572
+ return params
573
+
574
+ def select_header_accept(self, accepts):
575
+ """Returns `Accept` based on an array of accepts provided.
576
+
577
+ :param accepts: List of headers.
578
+ :return: Accept (e.g. application/json).
579
+ """
580
+ if not accepts:
581
+ return
582
+
583
+ accepts = [x.lower() for x in accepts]
584
+
585
+ if 'application/json' in accepts:
586
+ return 'application/json'
587
+ else:
588
+ return ', '.join(accepts)
589
+
590
+ def select_header_content_type(self, content_types, method=None, body=None):
591
+ """Returns `Content-Type` based on an array of content_types provided.
592
+
593
+ :param content_types: List of content-types.
594
+ :param method: http method (e.g. POST, PATCH).
595
+ :param body: http body to send.
596
+ :return: Content-Type (e.g. application/json).
597
+ """
598
+ if not content_types:
599
+ return None
600
+
601
+ content_types = [x.lower() for x in content_types]
602
+
603
+ if (method == 'PATCH' and
604
+ 'application/json-patch+json' in content_types and
605
+ isinstance(body, list)):
606
+ return 'application/json-patch+json'
607
+
608
+ if 'application/json' in content_types or '*/*' in content_types:
609
+ return 'application/json'
610
+ else:
611
+ return content_types[0]
612
+
613
+ def update_params_for_auth(self, headers, queries, auth_settings,
614
+ resource_path, method, body, request_auths=None):
615
+ """Updates header and query params based on authentication setting.
616
+
617
+ :param headers: Header parameters dict to be updated.
618
+ :param queries: Query parameters tuple list to be updated.
619
+ :param auth_settings: Authentication setting identifiers list.
620
+ :param resource_path: A string representation of the HTTP request resource path.
621
+ :param method: A string representation of the HTTP request method.
622
+ :param body: A object representing the body of the HTTP request.
623
+ The object type is the return value of _encoder.default().
624
+ :param request_auths: if set, the provided settings will
625
+ override the token in the configuration.
626
+ """
627
+ if not auth_settings:
628
+ return
629
+
630
+ if request_auths:
631
+ for auth_setting in request_auths:
632
+ self._apply_auth_params(
633
+ headers, queries, resource_path, method, body, auth_setting)
634
+ return
635
+
636
+ for auth in auth_settings:
637
+ auth_setting = self.configuration.auth_settings().get(auth)
638
+ if auth_setting:
639
+ self._apply_auth_params(
640
+ headers, queries, resource_path, method, body, auth_setting)
641
+
642
+ def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting):
643
+ if auth_setting['in'] == 'cookie':
644
+ headers['Cookie'] = auth_setting['key'] + "=" + auth_setting['value']
645
+ elif auth_setting['in'] == 'header':
646
+ if auth_setting['type'] != 'http-signature':
647
+ headers[auth_setting['key']] = auth_setting['value']
648
+ elif auth_setting['in'] == 'query':
649
+ queries.append((auth_setting['key'], auth_setting['value']))
650
+ else:
651
+ raise ApiValueError(
652
+ 'Authentication token must be in `query` or `header`'
653
+ )
654
+
655
+
656
+ class Endpoint(object):
657
+ def __init__(self, settings=None, params_map=None, root_map=None,
658
+ headers_map=None, api_client=None, callable=None):
659
+ """Creates an endpoint
660
+
661
+ Args:
662
+ settings (dict): see below key value pairs
663
+ 'response_type' (tuple/None): response type
664
+ 'auth' (list): a list of auth type keys
665
+ 'endpoint_path' (str): the endpoint path
666
+ 'operation_id' (str): endpoint string identifier
667
+ 'http_method' (str): POST/PUT/PATCH/GET etc
668
+ 'servers' (list): list of str servers that this endpoint is at
669
+ params_map (dict): see below key value pairs
670
+ 'all' (list): list of str endpoint parameter names
671
+ 'required' (list): list of required parameter names
672
+ 'nullable' (list): list of nullable parameter names
673
+ 'enum' (list): list of parameters with enum values
674
+ 'validation' (list): list of parameters with validations
675
+ root_map
676
+ 'validations' (dict): the dict mapping endpoint parameter tuple
677
+ paths to their validation dictionaries
678
+ 'allowed_values' (dict): the dict mapping endpoint parameter
679
+ tuple paths to their allowed_values (enum) dictionaries
680
+ 'openapi_types' (dict): param_name to openapi type
681
+ 'attribute_map' (dict): param_name to camelCase name
682
+ 'location_map' (dict): param_name to 'body', 'file', 'form',
683
+ 'header', 'path', 'query'
684
+ collection_format_map (dict): param_name to `csv` etc.
685
+ headers_map (dict): see below key value pairs
686
+ 'accept' (list): list of Accept header strings
687
+ 'content_type' (list): list of Content-Type header strings
688
+ api_client (ApiClient) api client instance
689
+ callable (function): the function which is invoked when the
690
+ Endpoint is called
691
+ """
692
+ self.settings = settings
693
+ self.params_map = params_map
694
+ self.params_map['all'].extend([
695
+ 'async_req',
696
+ '_host_index',
697
+ '_preload_content',
698
+ '_request_timeout',
699
+ '_return_http_data_only',
700
+ '_check_input_type',
701
+ '_check_return_type',
702
+ '_content_type',
703
+ '_spec_property_naming',
704
+ '_request_auths'
705
+ ])
706
+ self.params_map['nullable'].extend(['_request_timeout'])
707
+ self.validations = root_map['validations']
708
+ self.allowed_values = root_map['allowed_values']
709
+ self.openapi_types = root_map['openapi_types']
710
+ extra_types = {
711
+ 'async_req': (bool,),
712
+ '_host_index': (none_type, int),
713
+ '_preload_content': (bool,),
714
+ '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]),
715
+ '_return_http_data_only': (bool,),
716
+ '_check_input_type': (bool,),
717
+ '_check_return_type': (bool,),
718
+ '_spec_property_naming': (bool,),
719
+ '_content_type': (none_type, str),
720
+ '_request_auths': (none_type, list)
721
+ }
722
+ self.openapi_types.update(extra_types)
723
+ self.attribute_map = root_map['attribute_map']
724
+ self.location_map = root_map['location_map']
725
+ self.collection_format_map = root_map['collection_format_map']
726
+ self.headers_map = headers_map
727
+ self.api_client = api_client
728
+ self.callable = callable
729
+
730
+ def __validate_inputs(self, kwargs):
731
+ for param in self.params_map['enum']:
732
+ if param in kwargs:
733
+ check_allowed_values(
734
+ self.allowed_values,
735
+ (param,),
736
+ kwargs[param]
737
+ )
738
+
739
+ for param in self.params_map['validation']:
740
+ if param in kwargs:
741
+ check_validations(
742
+ self.validations,
743
+ (param,),
744
+ kwargs[param],
745
+ configuration=self.api_client.configuration
746
+ )
747
+
748
+ if kwargs['_check_input_type'] is False:
749
+ return
750
+
751
+ for key, value in kwargs.items():
752
+ fixed_val = validate_and_convert_types(
753
+ value,
754
+ self.openapi_types[key],
755
+ [key],
756
+ kwargs['_spec_property_naming'],
757
+ kwargs['_check_input_type'],
758
+ configuration=self.api_client.configuration
759
+ )
760
+ kwargs[key] = fixed_val
761
+
762
+ def __gather_params(self, kwargs):
763
+ params = {
764
+ 'body': None,
765
+ 'collection_format': {},
766
+ 'file': {},
767
+ 'form': [],
768
+ 'header': {},
769
+ 'path': {},
770
+ 'query': []
771
+ }
772
+
773
+ for param_name, param_value in kwargs.items():
774
+ param_location = self.location_map.get(param_name)
775
+ if param_location is None:
776
+ continue
777
+ if param_location:
778
+ if param_location == 'body':
779
+ params['body'] = param_value
780
+ continue
781
+ base_name = self.attribute_map[param_name]
782
+ if (param_location == 'form' and
783
+ self.openapi_types[param_name] == (file_type,)):
784
+ params['file'][base_name] = [param_value]
785
+ elif (param_location == 'form' and
786
+ self.openapi_types[param_name] == ([file_type],)):
787
+ # param_value is already a list
788
+ params['file'][base_name] = param_value
789
+ elif param_location in {'form', 'query'}:
790
+ param_value_full = (base_name, param_value)
791
+ params[param_location].append(param_value_full)
792
+ if param_location not in {'form', 'query'}:
793
+ params[param_location][base_name] = param_value
794
+ collection_format = self.collection_format_map.get(param_name)
795
+ if collection_format:
796
+ params['collection_format'][base_name] = collection_format
797
+
798
+ return params
799
+
800
+ def __call__(self, *args, **kwargs):
801
+ """ This method is invoked when endpoints are called
802
+ Example:
803
+
804
+ api_instance = AccessControlApi()
805
+ api_instance.get_acl # this is an instance of the class Endpoint
806
+ api_instance.get_acl() # this invokes api_instance.get_acl.__call__()
807
+ which then invokes the callable functions stored in that endpoint at
808
+ api_instance.get_acl.callable or self.callable in this class
809
+
810
+ """
811
+ return self.callable(self, *args, **kwargs)
812
+
813
+ def call_with_http_info(self, **kwargs):
814
+
815
+ try:
816
+ index = self.api_client.configuration.server_operation_index.get(
817
+ self.settings['operation_id'], self.api_client.configuration.server_index
818
+ ) if kwargs['_host_index'] is None else kwargs['_host_index']
819
+ server_variables = self.api_client.configuration.server_operation_variables.get(
820
+ self.settings['operation_id'], self.api_client.configuration.server_variables
821
+ )
822
+ _host = self.api_client.configuration.get_host_from_settings(
823
+ index, variables=server_variables, servers=self.settings['servers']
824
+ )
825
+ except IndexError:
826
+ if self.settings['servers']:
827
+ raise ApiValueError(
828
+ "Invalid host index. Must be 0 <= index < %s" %
829
+ len(self.settings['servers'])
830
+ )
831
+ _host = None
832
+
833
+ for key, value in kwargs.items():
834
+ if key not in self.params_map['all']:
835
+ raise ApiTypeError(
836
+ "Got an unexpected parameter '%s'"
837
+ " to method `%s`" %
838
+ (key, self.settings['operation_id'])
839
+ )
840
+ # only throw this nullable ApiValueError if _check_input_type
841
+ # is False, if _check_input_type==True we catch this case
842
+ # in self.__validate_inputs
843
+ if (key not in self.params_map['nullable'] and value is None
844
+ and kwargs['_check_input_type'] is False):
845
+ raise ApiValueError(
846
+ "Value may not be None for non-nullable parameter `%s`"
847
+ " when calling `%s`" %
848
+ (key, self.settings['operation_id'])
849
+ )
850
+
851
+ for key in self.params_map['required']:
852
+ if key not in kwargs.keys():
853
+ raise ApiValueError(
854
+ "Missing the required parameter `%s` when calling "
855
+ "`%s`" % (key, self.settings['operation_id'])
856
+ )
857
+
858
+ self.__validate_inputs(kwargs)
859
+
860
+ params = self.__gather_params(kwargs)
861
+
862
+ accept_headers_list = self.headers_map['accept']
863
+ if accept_headers_list:
864
+ params['header']['Accept'] = self.api_client.select_header_accept(
865
+ accept_headers_list)
866
+
867
+ if kwargs.get('_content_type'):
868
+ params['header']['Content-Type'] = kwargs['_content_type']
869
+ else:
870
+ content_type_headers_list = self.headers_map['content_type']
871
+ if content_type_headers_list:
872
+ if params['body'] != "":
873
+ content_types_list = self.api_client.select_header_content_type(
874
+ content_type_headers_list, self.settings['http_method'],
875
+ params['body'])
876
+ if content_types_list:
877
+ params['header']['Content-Type'] = content_types_list
878
+
879
+ return self.api_client.call_api(
880
+ self.settings['endpoint_path'], self.settings['http_method'],
881
+ params['path'],
882
+ params['query'],
883
+ params['header'],
884
+ body=params['body'],
885
+ post_params=params['form'],
886
+ files=params['file'],
887
+ response_type=self.settings['response_type'],
888
+ auth_settings=self.settings['auth'],
889
+ async_req=kwargs['async_req'],
890
+ _check_type=kwargs['_check_return_type'],
891
+ _return_http_data_only=kwargs['_return_http_data_only'],
892
+ _preload_content=kwargs['_preload_content'],
893
+ _request_timeout=kwargs['_request_timeout'],
894
+ _host=_host,
895
+ _request_auths=kwargs['_request_auths'],
896
+ collection_formats=params['collection_format'])