crypticorn 2.16.0__py3-none-any.whl → 2.17.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 (164) hide show
  1. crypticorn/__init__.py +2 -2
  2. crypticorn/auth/client/api/admin_api.py +397 -13
  3. crypticorn/auth/client/api/auth_api.py +3610 -341
  4. crypticorn/auth/client/api/service_api.py +249 -7
  5. crypticorn/auth/client/api/user_api.py +2295 -179
  6. crypticorn/auth/client/api/wallet_api.py +1468 -81
  7. crypticorn/auth/client/configuration.py +2 -2
  8. crypticorn/auth/client/models/create_api_key_request.py +2 -1
  9. crypticorn/auth/client/models/get_api_keys200_response_inner.py +2 -1
  10. crypticorn/auth/client/rest.py +23 -4
  11. crypticorn/auth/main.py +8 -5
  12. crypticorn/cli/init.py +1 -1
  13. crypticorn/cli/templates/.env.docker.temp +3 -0
  14. crypticorn/cli/templates/.env.example.temp +4 -0
  15. crypticorn/cli/templates/Dockerfile +5 -2
  16. crypticorn/client.py +226 -59
  17. crypticorn/common/__init__.py +1 -0
  18. crypticorn/common/auth.py +45 -14
  19. crypticorn/common/decorators.py +1 -2
  20. crypticorn/common/enums.py +0 -2
  21. crypticorn/common/errors.py +10 -0
  22. crypticorn/common/metrics.py +30 -0
  23. crypticorn/common/middleware.py +94 -1
  24. crypticorn/common/pagination.py +252 -20
  25. crypticorn/common/router/admin_router.py +2 -2
  26. crypticorn/common/router/status_router.py +40 -2
  27. crypticorn/common/scopes.py +2 -2
  28. crypticorn/common/warnings.py +7 -0
  29. crypticorn/dex/__init__.py +6 -0
  30. crypticorn/dex/client/__init__.py +49 -0
  31. crypticorn/dex/client/api/__init__.py +6 -0
  32. crypticorn/dex/client/api/admin_api.py +2986 -0
  33. crypticorn/dex/client/api/signals_api.py +1798 -0
  34. crypticorn/dex/client/api/status_api.py +892 -0
  35. crypticorn/dex/client/api_client.py +758 -0
  36. crypticorn/dex/client/api_response.py +20 -0
  37. crypticorn/dex/client/configuration.py +620 -0
  38. crypticorn/dex/client/exceptions.py +220 -0
  39. crypticorn/dex/client/models/__init__.py +30 -0
  40. crypticorn/dex/client/models/api_error_identifier.py +121 -0
  41. crypticorn/dex/client/models/api_error_level.py +37 -0
  42. crypticorn/dex/client/models/api_error_type.py +37 -0
  43. crypticorn/dex/client/models/exception_detail.py +117 -0
  44. crypticorn/dex/client/models/log_level.py +38 -0
  45. crypticorn/dex/client/models/paginated_response_signal_with_token.py +134 -0
  46. crypticorn/dex/client/models/risk.py +86 -0
  47. crypticorn/dex/client/models/signal_overview_stats.py +158 -0
  48. crypticorn/dex/client/models/signal_volume.py +84 -0
  49. crypticorn/dex/client/models/signal_with_token.py +163 -0
  50. crypticorn/dex/client/models/token_data.py +127 -0
  51. crypticorn/dex/client/models/token_detail.py +116 -0
  52. crypticorn/dex/client/py.typed +0 -0
  53. crypticorn/dex/client/rest.py +217 -0
  54. crypticorn/dex/main.py +1 -0
  55. crypticorn/hive/client/api/admin_api.py +1173 -47
  56. crypticorn/hive/client/api/data_api.py +499 -17
  57. crypticorn/hive/client/api/models_api.py +1595 -87
  58. crypticorn/hive/client/api/status_api.py +397 -16
  59. crypticorn/hive/client/api_client.py +0 -5
  60. crypticorn/hive/client/models/api_error_identifier.py +1 -1
  61. crypticorn/hive/client/models/coin_info.py +1 -1
  62. crypticorn/hive/client/models/exception_detail.py +1 -1
  63. crypticorn/hive/client/models/target_info.py +1 -1
  64. crypticorn/hive/client/rest.py +23 -4
  65. crypticorn/hive/main.py +99 -25
  66. crypticorn/hive/utils.py +2 -2
  67. crypticorn/klines/client/api/admin_api.py +1173 -47
  68. crypticorn/klines/client/api/change_in_timeframe_api.py +269 -11
  69. crypticorn/klines/client/api/funding_rates_api.py +315 -11
  70. crypticorn/klines/client/api/ohlcv_data_api.py +390 -11
  71. crypticorn/klines/client/api/status_api.py +397 -16
  72. crypticorn/klines/client/api/symbols_api.py +216 -11
  73. crypticorn/klines/client/api/udf_api.py +1268 -51
  74. crypticorn/klines/client/api_client.py +0 -5
  75. crypticorn/klines/client/models/api_error_identifier.py +3 -1
  76. crypticorn/klines/client/models/exception_detail.py +1 -1
  77. crypticorn/klines/client/models/ohlcv.py +1 -1
  78. crypticorn/klines/client/models/symbol_group.py +1 -1
  79. crypticorn/klines/client/models/udf_config.py +1 -1
  80. crypticorn/klines/client/rest.py +23 -4
  81. crypticorn/klines/main.py +89 -12
  82. crypticorn/metrics/client/api/admin_api.py +1173 -47
  83. crypticorn/metrics/client/api/exchanges_api.py +1370 -145
  84. crypticorn/metrics/client/api/indicators_api.py +622 -17
  85. crypticorn/metrics/client/api/logs_api.py +296 -11
  86. crypticorn/metrics/client/api/marketcap_api.py +1207 -67
  87. crypticorn/metrics/client/api/markets_api.py +343 -11
  88. crypticorn/metrics/client/api/quote_currencies_api.py +228 -11
  89. crypticorn/metrics/client/api/status_api.py +397 -16
  90. crypticorn/metrics/client/api/tokens_api.py +382 -15
  91. crypticorn/metrics/client/api_client.py +0 -5
  92. crypticorn/metrics/client/configuration.py +4 -2
  93. crypticorn/metrics/client/models/exception_detail.py +1 -1
  94. crypticorn/metrics/client/models/exchange_mapping.py +1 -1
  95. crypticorn/metrics/client/models/marketcap_ranking.py +1 -1
  96. crypticorn/metrics/client/models/marketcap_symbol_ranking.py +1 -1
  97. crypticorn/metrics/client/models/ohlcv.py +1 -1
  98. crypticorn/metrics/client/rest.py +23 -4
  99. crypticorn/metrics/main.py +113 -19
  100. crypticorn/pay/client/api/admin_api.py +1585 -57
  101. crypticorn/pay/client/api/now_payments_api.py +961 -39
  102. crypticorn/pay/client/api/payments_api.py +562 -17
  103. crypticorn/pay/client/api/products_api.py +880 -30
  104. crypticorn/pay/client/api/status_api.py +397 -16
  105. crypticorn/pay/client/api_client.py +0 -5
  106. crypticorn/pay/client/configuration.py +2 -2
  107. crypticorn/pay/client/models/api_error_identifier.py +7 -7
  108. crypticorn/pay/client/models/exception_detail.py +1 -1
  109. crypticorn/pay/client/models/now_create_invoice_req.py +1 -1
  110. crypticorn/pay/client/models/now_create_invoice_res.py +1 -1
  111. crypticorn/pay/client/models/product.py +1 -1
  112. crypticorn/pay/client/models/product_create.py +1 -1
  113. crypticorn/pay/client/models/product_update.py +1 -1
  114. crypticorn/pay/client/models/scope.py +1 -0
  115. crypticorn/pay/client/rest.py +23 -4
  116. crypticorn/pay/main.py +10 -6
  117. crypticorn/trade/client/__init__.py +11 -1
  118. crypticorn/trade/client/api/__init__.py +0 -1
  119. crypticorn/trade/client/api/admin_api.py +1184 -55
  120. crypticorn/trade/client/api/api_keys_api.py +1678 -162
  121. crypticorn/trade/client/api/bots_api.py +7563 -187
  122. crypticorn/trade/client/api/exchanges_api.py +565 -19
  123. crypticorn/trade/client/api/notifications_api.py +1290 -116
  124. crypticorn/trade/client/api/orders_api.py +393 -55
  125. crypticorn/trade/client/api/status_api.py +397 -13
  126. crypticorn/trade/client/api/strategies_api.py +1133 -77
  127. crypticorn/trade/client/api/trading_actions_api.py +786 -65
  128. crypticorn/trade/client/models/__init__.py +11 -0
  129. crypticorn/trade/client/models/actions_count.py +88 -0
  130. crypticorn/trade/client/models/api_error_identifier.py +1 -0
  131. crypticorn/trade/client/models/bot.py +7 -18
  132. crypticorn/trade/client/models/bot_create.py +17 -1
  133. crypticorn/trade/client/models/bot_update.py +17 -1
  134. crypticorn/trade/client/models/exchange.py +6 -1
  135. crypticorn/trade/client/models/exchange_key.py +1 -1
  136. crypticorn/trade/client/models/exchange_key_balance.py +111 -0
  137. crypticorn/trade/client/models/exchange_key_create.py +17 -1
  138. crypticorn/trade/client/models/exchange_key_update.py +17 -1
  139. crypticorn/trade/client/models/execution_ids.py +1 -1
  140. crypticorn/trade/client/models/futures_balance.py +27 -25
  141. crypticorn/trade/client/models/notification.py +17 -1
  142. crypticorn/trade/client/models/notification_create.py +18 -2
  143. crypticorn/trade/client/models/notification_update.py +17 -1
  144. crypticorn/trade/client/models/orders_count.py +88 -0
  145. crypticorn/trade/client/models/paginated_response_futures_trading_action.py +134 -0
  146. crypticorn/trade/client/models/paginated_response_order.py +134 -0
  147. crypticorn/trade/client/models/pn_l.py +95 -0
  148. crypticorn/trade/client/models/post_futures_action.py +1 -1
  149. crypticorn/trade/client/models/spot_balance.py +109 -0
  150. crypticorn/trade/client/models/strategy.py +22 -4
  151. crypticorn/trade/client/models/strategy_create.py +23 -5
  152. crypticorn/trade/client/models/strategy_exchange_info.py +16 -4
  153. crypticorn/trade/client/models/strategy_update.py +19 -3
  154. crypticorn/trade/client/models/tpsl.py +4 -19
  155. crypticorn/trade/client/models/tpsl_create.py +6 -19
  156. crypticorn/trade/client/rest.py +23 -4
  157. crypticorn/trade/main.py +15 -12
  158. {crypticorn-2.16.0.dist-info → crypticorn-2.17.0.dist-info}/METADATA +65 -20
  159. {crypticorn-2.16.0.dist-info → crypticorn-2.17.0.dist-info}/RECORD +163 -128
  160. crypticorn/trade/client/api/futures_trading_panel_api.py +0 -1285
  161. {crypticorn-2.16.0.dist-info → crypticorn-2.17.0.dist-info}/WHEEL +0 -0
  162. {crypticorn-2.16.0.dist-info → crypticorn-2.17.0.dist-info}/entry_points.txt +0 -0
  163. {crypticorn-2.16.0.dist-info → crypticorn-2.17.0.dist-info}/licenses/LICENSE +0 -0
  164. {crypticorn-2.16.0.dist-info → crypticorn-2.17.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,758 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ DEX AI API
5
+
6
+ API for DEX AI
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ import datetime
16
+ from dateutil.parser import parse
17
+ from enum import Enum
18
+ import decimal
19
+ import json
20
+ import mimetypes
21
+ import os
22
+ import re
23
+ import tempfile
24
+
25
+ from urllib.parse import quote
26
+ from typing import Tuple, Optional, List, Dict, Union
27
+ from pydantic import SecretStr
28
+
29
+ from crypticorn.dex.client.configuration import Configuration
30
+ from crypticorn.dex.client.api_response import ApiResponse, T as ApiResponseT
31
+ import crypticorn.dex.client.models
32
+ from crypticorn.dex.client import rest
33
+ from crypticorn.dex.client.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
+
46
+ class ApiClient:
47
+ """Generic API client for OpenAPI client library builds.
48
+
49
+ OpenAPI generic API client. This client handles the client-
50
+ server communication, and is invariant across implementations. Specifics of
51
+ the methods and models for each application are generated from the OpenAPI
52
+ templates.
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
+ """
61
+
62
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
63
+ NATIVE_TYPES_MAPPING = {
64
+ "int": int,
65
+ "long": int, # TODO remove as only py3 is supported?
66
+ "float": float,
67
+ "str": str,
68
+ "bool": bool,
69
+ "date": datetime.date,
70
+ "datetime": datetime.datetime,
71
+ "decimal": decimal.Decimal,
72
+ "object": object,
73
+ }
74
+ _pool = None
75
+
76
+ def __init__(
77
+ self, configuration=None, header_name=None, header_value=None, cookie=None
78
+ ) -> None:
79
+ # use default configuration if none is provided
80
+ if configuration is None:
81
+ configuration = Configuration.get_default()
82
+ self.configuration = configuration
83
+
84
+ self.rest_client = rest.RESTClientObject(configuration)
85
+ self.default_headers = {}
86
+ if header_name is not None:
87
+ self.default_headers[header_name] = header_value
88
+ self.cookie = cookie
89
+ # Set default User-Agent.
90
+ self.user_agent = "OpenAPI-Generator/1.0.0/python"
91
+ self.client_side_validation = configuration.client_side_validation
92
+
93
+ async def __aenter__(self):
94
+ return self
95
+
96
+ async def __aexit__(self, exc_type, exc_value, traceback):
97
+ await self.close()
98
+
99
+ async def close(self):
100
+ await self.rest_client.close()
101
+
102
+ @property
103
+ def user_agent(self):
104
+ """User agent for this API client"""
105
+ return self.default_headers["User-Agent"]
106
+
107
+ @user_agent.setter
108
+ def user_agent(self, value):
109
+ self.default_headers["User-Agent"] = value
110
+
111
+ def set_default_header(self, header_name, header_value):
112
+ self.default_headers[header_name] = header_value
113
+
114
+ _default = None
115
+
116
+ @classmethod
117
+ def get_default(cls):
118
+ """Return new instance of ApiClient.
119
+
120
+ This method returns newly created, based on default constructor,
121
+ object of ApiClient class or returns a copy of default
122
+ ApiClient.
123
+
124
+ :return: The ApiClient object.
125
+ """
126
+ if cls._default is None:
127
+ cls._default = ApiClient()
128
+ return cls._default
129
+
130
+ @classmethod
131
+ def set_default(cls, default):
132
+ """Set default instance of ApiClient.
133
+
134
+ It stores default ApiClient.
135
+
136
+ :param default: object of ApiClient.
137
+ """
138
+ cls._default = default
139
+
140
+ def param_serialize(
141
+ self,
142
+ method,
143
+ resource_path,
144
+ path_params=None,
145
+ query_params=None,
146
+ header_params=None,
147
+ body=None,
148
+ post_params=None,
149
+ files=None,
150
+ auth_settings=None,
151
+ collection_formats=None,
152
+ _host=None,
153
+ _request_auth=None,
154
+ ) -> RequestSerialized:
155
+ """Builds the HTTP request params needed by the request.
156
+ :param method: Method to call.
157
+ :param resource_path: Path to method endpoint.
158
+ :param path_params: Path parameters in the url.
159
+ :param query_params: Query parameters in the url.
160
+ :param header_params: Header parameters to be
161
+ placed in the request header.
162
+ :param body: Request body.
163
+ :param post_params dict: Request post form parameters,
164
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
165
+ :param auth_settings list: Auth Settings names for the request.
166
+ :param files dict: key -> filename, value -> filepath,
167
+ for `multipart/form-data`.
168
+ :param collection_formats: dict of collection formats for path, query,
169
+ header, and post parameters.
170
+ :param _request_auth: set to override the auth_settings for an a single
171
+ request; this effectively ignores the authentication
172
+ in the spec for a single request.
173
+ :return: tuple of form (path, http_method, query_params, header_params,
174
+ body, post_params, files)
175
+ """
176
+
177
+ config = self.configuration
178
+
179
+ # header parameters
180
+ header_params = header_params or {}
181
+ header_params.update(self.default_headers)
182
+ if self.cookie:
183
+ header_params["Cookie"] = self.cookie
184
+ if header_params:
185
+ header_params = self.sanitize_for_serialization(header_params)
186
+ header_params = dict(
187
+ self.parameters_to_tuples(header_params, collection_formats)
188
+ )
189
+
190
+ # path parameters
191
+ if path_params:
192
+ path_params = self.sanitize_for_serialization(path_params)
193
+ path_params = self.parameters_to_tuples(path_params, collection_formats)
194
+ for k, v in path_params:
195
+ # specified safe chars, encode everything
196
+ resource_path = resource_path.replace(
197
+ "{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param)
198
+ )
199
+
200
+ # post parameters
201
+ if post_params or files:
202
+ post_params = post_params if post_params else []
203
+ post_params = self.sanitize_for_serialization(post_params)
204
+ post_params = self.parameters_to_tuples(post_params, collection_formats)
205
+ if files:
206
+ post_params.extend(self.files_parameters(files))
207
+
208
+ # auth setting
209
+ self.update_params_for_auth(
210
+ header_params,
211
+ query_params,
212
+ auth_settings,
213
+ resource_path,
214
+ method,
215
+ body,
216
+ request_auth=_request_auth,
217
+ )
218
+
219
+ # body
220
+ if body:
221
+ body = self.sanitize_for_serialization(body)
222
+
223
+ # request url
224
+ if _host is None or self.configuration.ignore_operation_servers:
225
+ url = self.configuration.host + resource_path
226
+ else:
227
+ # use server/host defined in path or operation instead
228
+ url = _host + resource_path
229
+
230
+ # query parameters
231
+ if query_params:
232
+ query_params = self.sanitize_for_serialization(query_params)
233
+ url_query = self.parameters_to_url_query(query_params, collection_formats)
234
+ url += "?" + url_query
235
+
236
+ return method, url, header_params, body, post_params
237
+
238
+ async def call_api(
239
+ self,
240
+ method,
241
+ url,
242
+ header_params=None,
243
+ body=None,
244
+ post_params=None,
245
+ _request_timeout=None,
246
+ ) -> rest.RESTResponse:
247
+ """Makes the HTTP request (synchronous)
248
+ :param method: Method to call.
249
+ :param url: Path to method endpoint.
250
+ :param header_params: Header parameters to be
251
+ placed in the request header.
252
+ :param body: Request body.
253
+ :param post_params dict: Request post form parameters,
254
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
255
+ :param _request_timeout: timeout setting for this request.
256
+ :return: RESTResponse
257
+ """
258
+
259
+ try:
260
+ # perform request and return response
261
+ response_data = await self.rest_client.request(
262
+ method,
263
+ url,
264
+ headers=header_params,
265
+ body=body,
266
+ post_params=post_params,
267
+ _request_timeout=_request_timeout,
268
+ )
269
+
270
+ except ApiException as e:
271
+ raise e
272
+
273
+ return response_data
274
+
275
+ def response_deserialize(
276
+ self,
277
+ response_data: rest.RESTResponse,
278
+ response_types_map: Optional[Dict[str, ApiResponseT]] = None,
279
+ ) -> ApiResponse[ApiResponseT]:
280
+ """Deserializes response into an object.
281
+ :param response_data: RESTResponse object to be deserialized.
282
+ :param response_types_map: dict of response types.
283
+ :return: ApiResponse
284
+ """
285
+
286
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
287
+ assert response_data.data is not None, msg
288
+
289
+ response_type = response_types_map.get(str(response_data.status), None)
290
+ if (
291
+ not response_type
292
+ and isinstance(response_data.status, int)
293
+ and 100 <= response_data.status <= 599
294
+ ):
295
+ # if not found, look for '1XX', '2XX', etc.
296
+ response_type = response_types_map.get(
297
+ str(response_data.status)[0] + "XX", None
298
+ )
299
+
300
+ # deserialize response data
301
+ response_text = None
302
+ return_data = None
303
+ try:
304
+ if response_type == "bytearray":
305
+ return_data = response_data.data
306
+ elif response_type == "file":
307
+ return_data = self.__deserialize_file(response_data)
308
+ elif response_type is not None:
309
+ match = None
310
+ content_type = response_data.getheader("content-type")
311
+ if content_type is not None:
312
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
313
+ encoding = match.group(1) if match else "utf-8"
314
+ response_text = response_data.data.decode(encoding)
315
+ return_data = self.deserialize(
316
+ response_text, response_type, content_type
317
+ )
318
+ finally:
319
+ if not 200 <= response_data.status <= 299:
320
+ raise ApiException.from_response(
321
+ http_resp=response_data,
322
+ body=response_text,
323
+ data=return_data,
324
+ )
325
+
326
+ return ApiResponse(
327
+ status_code=response_data.status,
328
+ data=return_data,
329
+ headers=response_data.getheaders(),
330
+ raw_data=response_data.data,
331
+ )
332
+
333
+ def sanitize_for_serialization(self, obj):
334
+ """Builds a JSON POST object.
335
+
336
+ If obj is None, return None.
337
+ If obj is SecretStr, return obj.get_secret_value()
338
+ If obj is str, int, long, float, bool, return directly.
339
+ If obj is datetime.datetime, datetime.date
340
+ convert to string in iso8601 format.
341
+ If obj is decimal.Decimal return string representation.
342
+ If obj is list, sanitize each element in the list.
343
+ If obj is dict, return the dict.
344
+ If obj is OpenAPI model, return the properties dict.
345
+
346
+ :param obj: The data to serialize.
347
+ :return: The serialized form of data.
348
+ """
349
+ if obj is None:
350
+ return None
351
+ elif isinstance(obj, Enum):
352
+ return obj.value
353
+ elif isinstance(obj, SecretStr):
354
+ return obj.get_secret_value()
355
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
356
+ return obj
357
+ elif isinstance(obj, list):
358
+ return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
359
+ elif isinstance(obj, tuple):
360
+ return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj)
361
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
362
+ return obj.isoformat()
363
+ elif isinstance(obj, decimal.Decimal):
364
+ return str(obj)
365
+
366
+ elif isinstance(obj, dict):
367
+ obj_dict = obj
368
+ else:
369
+ # Convert model obj to dict except
370
+ # attributes `openapi_types`, `attribute_map`
371
+ # and attributes which value is not None.
372
+ # Convert attribute name to json key in
373
+ # model definition for request.
374
+ if hasattr(obj, "to_dict") and callable(getattr(obj, "to_dict")):
375
+ obj_dict = obj.to_dict()
376
+ else:
377
+ obj_dict = obj.__dict__
378
+
379
+ return {
380
+ key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()
381
+ }
382
+
383
+ def deserialize(
384
+ self, response_text: str, response_type: str, content_type: Optional[str]
385
+ ):
386
+ """Deserializes response into an object.
387
+
388
+ :param response: RESTResponse object to be deserialized.
389
+ :param response_type: class literal for
390
+ deserialized object, or string of class name.
391
+ :param content_type: content type of response.
392
+
393
+ :return: deserialized object.
394
+ """
395
+
396
+ # fetch data from response object
397
+ if content_type is None:
398
+ try:
399
+ data = json.loads(response_text)
400
+ except ValueError:
401
+ data = response_text
402
+ elif re.match(
403
+ r"^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)",
404
+ content_type,
405
+ re.IGNORECASE,
406
+ ):
407
+ if response_text == "":
408
+ data = ""
409
+ else:
410
+ data = json.loads(response_text)
411
+ elif re.match(r"^text\/[a-z.+-]+\s*(;|$)", content_type, re.IGNORECASE):
412
+ data = response_text
413
+ else:
414
+ raise ApiException(
415
+ status=0, reason="Unsupported content type: {0}".format(content_type)
416
+ )
417
+
418
+ return self.__deserialize(data, response_type)
419
+
420
+ def __deserialize(self, data, klass):
421
+ """Deserializes dict, list, str into an object.
422
+
423
+ :param data: dict, list or str.
424
+ :param klass: class literal, or string of class name.
425
+
426
+ :return: object.
427
+ """
428
+ if data is None:
429
+ return None
430
+
431
+ if isinstance(klass, str):
432
+ if klass.startswith("List["):
433
+ m = re.match(r"List\[(.*)]", klass)
434
+ assert m is not None, "Malformed List type definition"
435
+ sub_kls = m.group(1)
436
+ return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
437
+
438
+ if klass.startswith("Dict["):
439
+ m = re.match(r"Dict\[([^,]*), (.*)]", klass)
440
+ assert m is not None, "Malformed Dict type definition"
441
+ sub_kls = m.group(2)
442
+ return {k: self.__deserialize(v, sub_kls) for k, v in data.items()}
443
+
444
+ # convert str to class
445
+ if klass in self.NATIVE_TYPES_MAPPING:
446
+ klass = self.NATIVE_TYPES_MAPPING[klass]
447
+ else:
448
+ klass = getattr(crypticorn.dex.client.models, klass)
449
+
450
+ if klass in self.PRIMITIVE_TYPES:
451
+ return self.__deserialize_primitive(data, klass)
452
+ elif klass == object:
453
+ return self.__deserialize_object(data)
454
+ elif klass == datetime.date:
455
+ return self.__deserialize_date(data)
456
+ elif klass == datetime.datetime:
457
+ return self.__deserialize_datetime(data)
458
+ elif klass == decimal.Decimal:
459
+ return decimal.Decimal(data)
460
+ elif issubclass(klass, Enum):
461
+ return self.__deserialize_enum(data, klass)
462
+ else:
463
+ return self.__deserialize_model(data, klass)
464
+
465
+ def parameters_to_tuples(self, params, collection_formats):
466
+ """Get parameters as list of tuples, formatting collections.
467
+
468
+ :param params: Parameters as dict or list of two-tuples
469
+ :param dict collection_formats: Parameter collection formats
470
+ :return: Parameters as list of tuples, collections formatted
471
+ """
472
+ new_params: List[Tuple[str, str]] = []
473
+ if collection_formats is None:
474
+ collection_formats = {}
475
+ for k, v in params.items() if isinstance(params, dict) else params:
476
+ if k in collection_formats:
477
+ collection_format = collection_formats[k]
478
+ if collection_format == "multi":
479
+ new_params.extend((k, value) for value in v)
480
+ else:
481
+ if collection_format == "ssv":
482
+ delimiter = " "
483
+ elif collection_format == "tsv":
484
+ delimiter = "\t"
485
+ elif collection_format == "pipes":
486
+ delimiter = "|"
487
+ else: # csv is the default
488
+ delimiter = ","
489
+ new_params.append((k, delimiter.join(str(value) for value in v)))
490
+ else:
491
+ new_params.append((k, v))
492
+ return new_params
493
+
494
+ def parameters_to_url_query(self, params, collection_formats):
495
+ """Get parameters as list of tuples, formatting collections.
496
+
497
+ :param params: Parameters as dict or list of two-tuples
498
+ :param dict collection_formats: Parameter collection formats
499
+ :return: URL query string (e.g. a=Hello%20World&b=123)
500
+ """
501
+ new_params: List[Tuple[str, str]] = []
502
+ if collection_formats is None:
503
+ collection_formats = {}
504
+ for k, v in params.items() if isinstance(params, dict) else params:
505
+ if isinstance(v, bool):
506
+ v = str(v).lower()
507
+ if isinstance(v, (int, float)):
508
+ v = str(v)
509
+ if isinstance(v, dict):
510
+ v = json.dumps(v)
511
+
512
+ if k in collection_formats:
513
+ collection_format = collection_formats[k]
514
+ if collection_format == "multi":
515
+ new_params.extend((k, quote(str(value))) for value in v)
516
+ else:
517
+ if collection_format == "ssv":
518
+ delimiter = " "
519
+ elif collection_format == "tsv":
520
+ delimiter = "\t"
521
+ elif collection_format == "pipes":
522
+ delimiter = "|"
523
+ else: # csv is the default
524
+ delimiter = ","
525
+ new_params.append(
526
+ (k, delimiter.join(quote(str(value)) for value in v))
527
+ )
528
+ else:
529
+ new_params.append((k, quote(str(v))))
530
+
531
+ return "&".join(["=".join(map(str, item)) for item in new_params])
532
+
533
+ def files_parameters(
534
+ self,
535
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
536
+ ):
537
+ """Builds form parameters.
538
+
539
+ :param files: File parameters.
540
+ :return: Form parameters with files.
541
+ """
542
+ params = []
543
+ for k, v in files.items():
544
+ if isinstance(v, str):
545
+ with open(v, "rb") as f:
546
+ filename = os.path.basename(f.name)
547
+ filedata = f.read()
548
+ elif isinstance(v, bytes):
549
+ filename = k
550
+ filedata = v
551
+ elif isinstance(v, tuple):
552
+ filename, filedata = v
553
+ elif isinstance(v, list):
554
+ for file_param in v:
555
+ params.extend(self.files_parameters({k: file_param}))
556
+ continue
557
+ else:
558
+ raise ValueError("Unsupported file value")
559
+ mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
560
+ params.append(tuple([k, tuple([filename, filedata, mimetype])]))
561
+ return params
562
+
563
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
564
+ """Returns `Accept` based on an array of accepts provided.
565
+
566
+ :param accepts: List of headers.
567
+ :return: Accept (e.g. application/json).
568
+ """
569
+ if not accepts:
570
+ return None
571
+
572
+ for accept in accepts:
573
+ if re.search("json", accept, re.IGNORECASE):
574
+ return accept
575
+
576
+ return accepts[0]
577
+
578
+ def select_header_content_type(self, content_types):
579
+ """Returns `Content-Type` based on an array of content_types provided.
580
+
581
+ :param content_types: List of content-types.
582
+ :return: Content-Type (e.g. application/json).
583
+ """
584
+ if not content_types:
585
+ return None
586
+
587
+ for content_type in content_types:
588
+ if re.search("json", content_type, re.IGNORECASE):
589
+ return content_type
590
+
591
+ return content_types[0]
592
+
593
+ def update_params_for_auth(
594
+ self,
595
+ headers,
596
+ queries,
597
+ auth_settings,
598
+ resource_path,
599
+ method,
600
+ body,
601
+ request_auth=None,
602
+ ) -> None:
603
+ """Updates header and query params based on authentication setting.
604
+
605
+ :param headers: Header parameters dict to be updated.
606
+ :param queries: Query parameters tuple list to be updated.
607
+ :param auth_settings: Authentication setting identifiers list.
608
+ :resource_path: A string representation of the HTTP request resource path.
609
+ :method: A string representation of the HTTP request method.
610
+ :body: A object representing the body of the HTTP request.
611
+ The object type is the return value of sanitize_for_serialization().
612
+ :param request_auth: if set, the provided settings will
613
+ override the token in the configuration.
614
+ """
615
+ if not auth_settings:
616
+ return
617
+
618
+ if request_auth:
619
+ self._apply_auth_params(
620
+ headers, queries, resource_path, method, body, request_auth
621
+ )
622
+ else:
623
+ for auth in auth_settings:
624
+ auth_setting = self.configuration.auth_settings().get(auth)
625
+ if auth_setting:
626
+ self._apply_auth_params(
627
+ headers, queries, resource_path, method, body, auth_setting
628
+ )
629
+
630
+ def _apply_auth_params(
631
+ self, headers, queries, resource_path, method, body, auth_setting
632
+ ) -> None:
633
+ """Updates the request parameters based on a single auth_setting
634
+
635
+ :param headers: Header parameters dict to be updated.
636
+ :param queries: Query parameters tuple list to be updated.
637
+ :resource_path: A string representation of the HTTP request resource path.
638
+ :method: A string representation of the HTTP request method.
639
+ :body: A object representing the body of the HTTP request.
640
+ The object type is the return value of sanitize_for_serialization().
641
+ :param auth_setting: auth settings for the endpoint
642
+ """
643
+ if auth_setting["in"] == "cookie":
644
+ headers["Cookie"] = 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("Authentication token must be in `query` or `header`")
652
+
653
+ def __deserialize_file(self, response):
654
+ """Deserializes body to file
655
+
656
+ Saves response body into a file in a temporary folder,
657
+ using the filename from the `Content-Disposition` header if provided.
658
+
659
+ handle file downloading
660
+ save response body into a tmp file and return the instance
661
+
662
+ :param response: RESTResponse.
663
+ :return: file path.
664
+ """
665
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
666
+ os.close(fd)
667
+ os.remove(path)
668
+
669
+ content_disposition = response.getheader("Content-Disposition")
670
+ if content_disposition:
671
+ m = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition)
672
+ assert m is not None, "Unexpected 'content-disposition' header value"
673
+ filename = m.group(1)
674
+ path = os.path.join(os.path.dirname(path), filename)
675
+
676
+ with open(path, "wb") as f:
677
+ f.write(response.data)
678
+
679
+ return path
680
+
681
+ def __deserialize_primitive(self, data, klass):
682
+ """Deserializes string to primitive type.
683
+
684
+ :param data: str.
685
+ :param klass: class literal.
686
+
687
+ :return: int, long, float, str, bool.
688
+ """
689
+ try:
690
+ return klass(data)
691
+ except UnicodeEncodeError:
692
+ return str(data)
693
+ except TypeError:
694
+ return data
695
+
696
+ def __deserialize_object(self, value):
697
+ """Return an original value.
698
+
699
+ :return: object.
700
+ """
701
+ return value
702
+
703
+ def __deserialize_date(self, string):
704
+ """Deserializes string to date.
705
+
706
+ :param string: str.
707
+ :return: date.
708
+ """
709
+ try:
710
+ return parse(string).date()
711
+ except ImportError:
712
+ return string
713
+ except ValueError:
714
+ raise rest.ApiException(
715
+ status=0, reason="Failed to parse `{0}` as date object".format(string)
716
+ )
717
+
718
+ def __deserialize_datetime(self, string):
719
+ """Deserializes string to datetime.
720
+
721
+ The string should be in iso8601 datetime format.
722
+
723
+ :param string: str.
724
+ :return: datetime.
725
+ """
726
+ try:
727
+ return parse(string)
728
+ except ImportError:
729
+ return string
730
+ except ValueError:
731
+ raise rest.ApiException(
732
+ status=0,
733
+ reason=("Failed to parse `{0}` as datetime object".format(string)),
734
+ )
735
+
736
+ def __deserialize_enum(self, data, klass):
737
+ """Deserializes primitive type to enum.
738
+
739
+ :param data: primitive type.
740
+ :param klass: class literal.
741
+ :return: enum value.
742
+ """
743
+ try:
744
+ return klass(data)
745
+ except ValueError:
746
+ raise rest.ApiException(
747
+ status=0, reason=("Failed to parse `{0}` as `{1}`".format(data, klass))
748
+ )
749
+
750
+ def __deserialize_model(self, data, klass):
751
+ """Deserializes list or dict to model.
752
+
753
+ :param data: dict, list.
754
+ :param klass: class literal.
755
+ :return: model object.
756
+ """
757
+
758
+ return klass.from_dict(data)