kalshi-python-async 3.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 (151) hide show
  1. kalshi_python_async/__init__.py +272 -0
  2. kalshi_python_async/api/__init__.py +19 -0
  3. kalshi_python_async/api/api_keys_api.py +1098 -0
  4. kalshi_python_async/api/communications_api.py +3216 -0
  5. kalshi_python_async/api/events_api.py +1941 -0
  6. kalshi_python_async/api/exchange_api.py +1263 -0
  7. kalshi_python_async/api/fcm_api.py +792 -0
  8. kalshi_python_async/api/incentive_programs_api.py +346 -0
  9. kalshi_python_async/api/live_data_api.py +564 -0
  10. kalshi_python_async/api/market_api.py +2568 -0
  11. kalshi_python_async/api/milestone_api.py +689 -0
  12. kalshi_python_async/api/multivariate_api.py +1486 -0
  13. kalshi_python_async/api/order_groups_api.py +1375 -0
  14. kalshi_python_async/api/orders_api.py +2913 -0
  15. kalshi_python_async/api/portfolio_api.py +1572 -0
  16. kalshi_python_async/api/search_api.py +516 -0
  17. kalshi_python_async/api/structured_targets_api.py +605 -0
  18. kalshi_python_async/api_client.py +833 -0
  19. kalshi_python_async/api_response.py +21 -0
  20. kalshi_python_async/auth.py +89 -0
  21. kalshi_python_async/configuration.py +622 -0
  22. kalshi_python_async/exceptions.py +216 -0
  23. kalshi_python_async/models/__init__.py +136 -0
  24. kalshi_python_async/models/accept_quote_request.py +94 -0
  25. kalshi_python_async/models/amend_order_request.py +120 -0
  26. kalshi_python_async/models/amend_order_response.py +96 -0
  27. kalshi_python_async/models/announcement.py +108 -0
  28. kalshi_python_async/models/api_key.py +89 -0
  29. kalshi_python_async/models/associated_event.py +105 -0
  30. kalshi_python_async/models/batch_cancel_orders_individual_response.py +111 -0
  31. kalshi_python_async/models/batch_cancel_orders_request.py +87 -0
  32. kalshi_python_async/models/batch_cancel_orders_response.py +95 -0
  33. kalshi_python_async/models/batch_create_orders_individual_response.py +114 -0
  34. kalshi_python_async/models/batch_create_orders_request.py +95 -0
  35. kalshi_python_async/models/batch_create_orders_response.py +95 -0
  36. kalshi_python_async/models/batch_get_market_candlesticks_response.py +95 -0
  37. kalshi_python_async/models/bid_ask_distribution.py +101 -0
  38. kalshi_python_async/models/cancel_order_response.py +93 -0
  39. kalshi_python_async/models/create_api_key_request.py +89 -0
  40. kalshi_python_async/models/create_api_key_response.py +87 -0
  41. kalshi_python_async/models/create_market_in_multivariate_event_collection_request.py +95 -0
  42. kalshi_python_async/models/create_market_in_multivariate_event_collection_response.py +89 -0
  43. kalshi_python_async/models/create_order_group_request.py +88 -0
  44. kalshi_python_async/models/create_order_group_response.py +87 -0
  45. kalshi_python_async/models/create_order_request.py +159 -0
  46. kalshi_python_async/models/create_order_response.py +91 -0
  47. kalshi_python_async/models/create_quote_request.py +93 -0
  48. kalshi_python_async/models/create_quote_response.py +87 -0
  49. kalshi_python_async/models/create_rfq_request.py +97 -0
  50. kalshi_python_async/models/create_rfq_response.py +87 -0
  51. kalshi_python_async/models/daily_schedule.py +89 -0
  52. kalshi_python_async/models/decrease_order_request.py +90 -0
  53. kalshi_python_async/models/decrease_order_response.py +91 -0
  54. kalshi_python_async/models/error_response.py +93 -0
  55. kalshi_python_async/models/event_data.py +133 -0
  56. kalshi_python_async/models/event_position.py +105 -0
  57. kalshi_python_async/models/exchange_status.py +97 -0
  58. kalshi_python_async/models/fill.py +134 -0
  59. kalshi_python_async/models/forecast_percentiles_point.py +101 -0
  60. kalshi_python_async/models/generate_api_key_request.py +87 -0
  61. kalshi_python_async/models/generate_api_key_response.py +89 -0
  62. kalshi_python_async/models/get_api_keys_response.py +95 -0
  63. kalshi_python_async/models/get_balance_response.py +91 -0
  64. kalshi_python_async/models/get_communications_id_response.py +87 -0
  65. kalshi_python_async/models/get_event_candlesticks_response.py +104 -0
  66. kalshi_python_async/models/get_event_forecast_percentiles_history_response.py +95 -0
  67. kalshi_python_async/models/get_event_metadata_response.py +123 -0
  68. kalshi_python_async/models/get_event_response.py +101 -0
  69. kalshi_python_async/models/get_events_candlesticks_response.py +95 -0
  70. kalshi_python_async/models/get_events_candlesticks_response_events_inner.py +106 -0
  71. kalshi_python_async/models/get_events_response.py +107 -0
  72. kalshi_python_async/models/get_exchange_announcements_response.py +95 -0
  73. kalshi_python_async/models/get_exchange_schedule_response.py +91 -0
  74. kalshi_python_async/models/get_fills_response.py +97 -0
  75. kalshi_python_async/models/get_filters_by_sports_response.py +102 -0
  76. kalshi_python_async/models/get_incentive_programs_response.py +97 -0
  77. kalshi_python_async/models/get_live_data_response.py +91 -0
  78. kalshi_python_async/models/get_live_datas_response.py +95 -0
  79. kalshi_python_async/models/get_market_candlesticks_response.py +97 -0
  80. kalshi_python_async/models/get_market_orderbook_response.py +91 -0
  81. kalshi_python_async/models/get_market_response.py +91 -0
  82. kalshi_python_async/models/get_markets_response.py +97 -0
  83. kalshi_python_async/models/get_milestone_response.py +91 -0
  84. kalshi_python_async/models/get_milestones_response.py +97 -0
  85. kalshi_python_async/models/get_multivariate_event_collection_lookup_history_response.py +95 -0
  86. kalshi_python_async/models/get_multivariate_event_collection_response.py +91 -0
  87. kalshi_python_async/models/get_multivariate_event_collections_response.py +97 -0
  88. kalshi_python_async/models/get_multivariate_events_response.py +97 -0
  89. kalshi_python_async/models/get_order_group_response.py +89 -0
  90. kalshi_python_async/models/get_order_groups_response.py +95 -0
  91. kalshi_python_async/models/get_order_queue_position_response.py +87 -0
  92. kalshi_python_async/models/get_order_queue_positions_response.py +95 -0
  93. kalshi_python_async/models/get_order_response.py +91 -0
  94. kalshi_python_async/models/get_orders_response.py +97 -0
  95. kalshi_python_async/models/get_portfolio_resting_order_total_value_response.py +87 -0
  96. kalshi_python_async/models/get_positions_response.py +107 -0
  97. kalshi_python_async/models/get_quote_response.py +91 -0
  98. kalshi_python_async/models/get_quotes_response.py +97 -0
  99. kalshi_python_async/models/get_rfq_response.py +91 -0
  100. kalshi_python_async/models/get_rfqs_response.py +97 -0
  101. kalshi_python_async/models/get_series_fee_changes_response.py +95 -0
  102. kalshi_python_async/models/get_series_list_response.py +95 -0
  103. kalshi_python_async/models/get_series_response.py +91 -0
  104. kalshi_python_async/models/get_settlements_response.py +97 -0
  105. kalshi_python_async/models/get_structured_target_response.py +91 -0
  106. kalshi_python_async/models/get_structured_targets_response.py +97 -0
  107. kalshi_python_async/models/get_tags_for_series_categories_response.py +87 -0
  108. kalshi_python_async/models/get_trades_response.py +97 -0
  109. kalshi_python_async/models/get_user_data_timestamp_response.py +88 -0
  110. kalshi_python_async/models/incentive_program.py +121 -0
  111. kalshi_python_async/models/live_data.py +91 -0
  112. kalshi_python_async/models/lookup_point.py +102 -0
  113. kalshi_python_async/models/lookup_tickers_for_market_in_multivariate_event_collection_request.py +95 -0
  114. kalshi_python_async/models/lookup_tickers_for_market_in_multivariate_event_collection_response.py +89 -0
  115. kalshi_python_async/models/maintenance_window.py +90 -0
  116. kalshi_python_async/models/market.py +307 -0
  117. kalshi_python_async/models/market_candlestick.py +108 -0
  118. kalshi_python_async/models/market_candlesticks_response.py +97 -0
  119. kalshi_python_async/models/market_metadata.py +91 -0
  120. kalshi_python_async/models/market_position.py +110 -0
  121. kalshi_python_async/models/milestone.py +120 -0
  122. kalshi_python_async/models/multivariate_event_collection.py +122 -0
  123. kalshi_python_async/models/mve_selected_leg.py +91 -0
  124. kalshi_python_async/models/order.py +189 -0
  125. kalshi_python_async/models/order_group.py +89 -0
  126. kalshi_python_async/models/order_queue_position.py +91 -0
  127. kalshi_python_async/models/order_status.py +38 -0
  128. kalshi_python_async/models/orderbook.py +94 -0
  129. kalshi_python_async/models/percentile_point.py +93 -0
  130. kalshi_python_async/models/price_distribution.py +157 -0
  131. kalshi_python_async/models/price_range.py +91 -0
  132. kalshi_python_async/models/quote.py +153 -0
  133. kalshi_python_async/models/rfq.py +129 -0
  134. kalshi_python_async/models/schedule.py +105 -0
  135. kalshi_python_async/models/scope_list.py +87 -0
  136. kalshi_python_async/models/self_trade_prevention_type.py +37 -0
  137. kalshi_python_async/models/series.py +129 -0
  138. kalshi_python_async/models/series_fee_change.py +103 -0
  139. kalshi_python_async/models/settlement.py +118 -0
  140. kalshi_python_async/models/settlement_source.py +89 -0
  141. kalshi_python_async/models/sport_filter_details.py +102 -0
  142. kalshi_python_async/models/structured_target.py +98 -0
  143. kalshi_python_async/models/ticker_pair.py +98 -0
  144. kalshi_python_async/models/trade.py +113 -0
  145. kalshi_python_async/models/weekly_schedule.py +154 -0
  146. kalshi_python_async/py.typed +0 -0
  147. kalshi_python_async/rest.py +213 -0
  148. kalshi_python_async-3.0.0.dist-info/METADATA +78 -0
  149. kalshi_python_async-3.0.0.dist-info/RECORD +151 -0
  150. kalshi_python_async-3.0.0.dist-info/WHEEL +5 -0
  151. kalshi_python_async-3.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,833 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Kalshi Trade API Manual Endpoints
5
+
6
+ Manually defined OpenAPI spec for endpoints being migrated to spec-first approach
7
+
8
+ The version of the OpenAPI document: 3.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
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 time
24
+ import base64
25
+
26
+ from urllib.parse import quote
27
+ from typing import Tuple, Optional, List, Dict, Union
28
+ from pydantic import SecretStr
29
+
30
+
31
+ from kalshi_python_async.configuration import Configuration
32
+ from kalshi_python_async.api_response import ApiResponse, T as ApiResponseT
33
+ import kalshi_python_async.models
34
+ from kalshi_python_async import rest
35
+ from kalshi_python_async.exceptions import (
36
+ ApiValueError,
37
+ ApiException,
38
+ BadRequestException,
39
+ UnauthorizedException,
40
+ ForbiddenException,
41
+ NotFoundException,
42
+ ServiceException
43
+ )
44
+
45
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
46
+
47
+ class ApiClient:
48
+ """Generic API client for OpenAPI client library builds.
49
+
50
+ OpenAPI generic API client. This client handles the client-
51
+ server communication, and is invariant across implementations. Specifics of
52
+ the methods and models for each application are generated from the OpenAPI
53
+ templates.
54
+
55
+ :param configuration: .Configuration object for this client
56
+ :param header_name: a header to pass when making calls to the API.
57
+ :param header_value: a header value to pass when making calls to
58
+ the API.
59
+ :param cookie: a cookie to include in the header when making calls
60
+ to the API
61
+ """
62
+
63
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
64
+ NATIVE_TYPES_MAPPING = {
65
+ 'int': int,
66
+ 'long': int, # TODO remove as only py3 is supported?
67
+ 'float': float,
68
+ 'str': str,
69
+ 'bool': bool,
70
+ 'date': datetime.date,
71
+ 'datetime': datetime.datetime,
72
+ 'decimal': decimal.Decimal,
73
+ 'object': object,
74
+ }
75
+ _pool = None
76
+
77
+ def __init__(
78
+ self,
79
+ configuration=None,
80
+ header_name=None,
81
+ header_value=None,
82
+ cookie=None
83
+ ) -> None:
84
+ # use default configuration if none is provided
85
+ if configuration is None:
86
+ configuration = Configuration.get_default()
87
+ self.configuration = configuration
88
+
89
+ self.rest_client = rest.RESTClientObject(configuration)
90
+ self.default_headers = {}
91
+ if header_name is not None:
92
+ self.default_headers[header_name] = header_value
93
+ self.cookie = cookie
94
+ # Set default User-Agent.
95
+ self.user_agent = 'OpenAPI-Generator/3.0.0/python'
96
+ self.client_side_validation = configuration.client_side_validation
97
+
98
+ # Kalshi authentication
99
+ self.kalshi_auth = None
100
+
101
+ async def __aenter__(self):
102
+ return self
103
+
104
+ async def __aexit__(self, exc_type, exc_value, traceback):
105
+ await self.close()
106
+
107
+ async def close(self):
108
+ await self.rest_client.close()
109
+
110
+ @property
111
+ def user_agent(self):
112
+ """User agent for this API client"""
113
+ return self.default_headers['User-Agent']
114
+
115
+ @user_agent.setter
116
+ def user_agent(self, value):
117
+ self.default_headers['User-Agent'] = value
118
+
119
+ def set_default_header(self, header_name, header_value):
120
+ self.default_headers[header_name] = header_value
121
+
122
+ def set_bearer_token(self, token: str):
123
+ """Set the bearer token for authorization.
124
+
125
+ This method automatically sets the Authorization header with the bearer token,
126
+ eliminating the need to manually call set_default_header.
127
+
128
+ Args:
129
+ token: The bearer token string
130
+ """
131
+ self.set_default_header('Authorization', f'Bearer {token}')
132
+
133
+ def set_kalshi_auth(self, key_id: str, private_key_path: str):
134
+ """Set up Kalshi authentication for this client.
135
+
136
+ Args:
137
+ key_id: Your Kalshi API key ID
138
+ private_key_path: Path to your RSA private key file
139
+ """
140
+ self.kalshi_auth = KalshiAuth(key_id, private_key_path)
141
+
142
+
143
+ _default = None
144
+
145
+ @classmethod
146
+ def get_default(cls):
147
+ """Return new instance of ApiClient.
148
+
149
+ This method returns newly created, based on default constructor,
150
+ object of ApiClient class or returns a copy of default
151
+ ApiClient.
152
+
153
+ :return: The ApiClient object.
154
+ """
155
+ if cls._default is None:
156
+ cls._default = ApiClient()
157
+ return cls._default
158
+
159
+ @classmethod
160
+ def set_default(cls, default):
161
+ """Set default instance of ApiClient.
162
+
163
+ It stores default ApiClient.
164
+
165
+ :param default: object of ApiClient.
166
+ """
167
+ cls._default = default
168
+
169
+ def param_serialize(
170
+ self,
171
+ method,
172
+ resource_path,
173
+ path_params=None,
174
+ query_params=None,
175
+ header_params=None,
176
+ body=None,
177
+ post_params=None,
178
+ files=None, auth_settings=None,
179
+ collection_formats=None,
180
+ _host=None,
181
+ _request_auth=None
182
+ ) -> RequestSerialized:
183
+
184
+ """Builds the HTTP request params needed by the request.
185
+ :param method: Method to call.
186
+ :param resource_path: Path to method endpoint.
187
+ :param path_params: Path parameters in the url.
188
+ :param query_params: Query parameters in the url.
189
+ :param header_params: Header parameters to be
190
+ placed in the request header.
191
+ :param body: Request body.
192
+ :param post_params dict: Request post form parameters,
193
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
194
+ :param auth_settings list: Auth Settings names for the request.
195
+ :param files dict: key -> filename, value -> filepath,
196
+ for `multipart/form-data`.
197
+ :param collection_formats: dict of collection formats for path, query,
198
+ header, and post parameters.
199
+ :param _request_auth: set to override the auth_settings for an a single
200
+ request; this effectively ignores the authentication
201
+ in the spec for a single request.
202
+ :return: tuple of form (path, http_method, query_params, header_params,
203
+ body, post_params, files)
204
+ """
205
+
206
+ config = self.configuration
207
+
208
+ # header parameters
209
+ header_params = header_params or {}
210
+ header_params.update(self.default_headers)
211
+ if self.cookie:
212
+ header_params['Cookie'] = self.cookie
213
+ if header_params:
214
+ header_params = self.sanitize_for_serialization(header_params)
215
+ header_params = dict(
216
+ self.parameters_to_tuples(header_params,collection_formats)
217
+ )
218
+
219
+ # path parameters
220
+ if path_params:
221
+ path_params = self.sanitize_for_serialization(path_params)
222
+ path_params = self.parameters_to_tuples(
223
+ path_params,
224
+ collection_formats
225
+ )
226
+ for k, v in path_params:
227
+ # specified safe chars, encode everything
228
+ resource_path = resource_path.replace(
229
+ '{%s}' % k,
230
+ quote(str(v), safe=config.safe_chars_for_path_param)
231
+ )
232
+
233
+ # post parameters
234
+ if post_params or files:
235
+ post_params = post_params if post_params else []
236
+ post_params = self.sanitize_for_serialization(post_params)
237
+ post_params = self.parameters_to_tuples(
238
+ post_params,
239
+ collection_formats
240
+ )
241
+ if files:
242
+ post_params.extend(self.files_parameters(files))
243
+
244
+ # auth setting
245
+ self.update_params_for_auth(
246
+ header_params,
247
+ query_params,
248
+ auth_settings,
249
+ resource_path,
250
+ method,
251
+ body,
252
+ request_auth=_request_auth
253
+ )
254
+
255
+ # body
256
+ if body:
257
+ body = self.sanitize_for_serialization(body)
258
+
259
+ # request url
260
+ if _host is None or self.configuration.ignore_operation_servers:
261
+ url = self.configuration.host + resource_path
262
+ else:
263
+ # use server/host defined in path or operation instead
264
+ url = _host + resource_path
265
+
266
+ # query parameters
267
+ if query_params:
268
+ query_params = self.sanitize_for_serialization(query_params)
269
+ url_query = self.parameters_to_url_query(
270
+ query_params,
271
+ collection_formats
272
+ )
273
+ url += "?" + url_query
274
+
275
+ return method, url, header_params, body, post_params
276
+
277
+
278
+ async def call_api(
279
+ self,
280
+ method,
281
+ url,
282
+ header_params=None,
283
+ body=None,
284
+ post_params=None,
285
+ _request_timeout=None
286
+ ) -> rest.RESTResponse:
287
+ """Makes the HTTP request (synchronous)
288
+ :param method: Method to call.
289
+ :param url: Path to method endpoint.
290
+ :param header_params: Header parameters to be
291
+ placed in the request header.
292
+ :param body: Request body.
293
+ :param post_params dict: Request post form parameters,
294
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
295
+ :param _request_timeout: timeout setting for this request.
296
+ :return: RESTResponse
297
+ """
298
+
299
+ if header_params is None:
300
+ header_params = {}
301
+
302
+ # Add Kalshi authentication headers if configured
303
+ if self.kalshi_auth:
304
+ auth_headers = self.kalshi_auth.create_auth_headers(method, url)
305
+ header_params.update(auth_headers)
306
+
307
+ try:
308
+ # perform request and return response
309
+ response_data = await self.rest_client.request(
310
+ method, url,
311
+ headers=header_params,
312
+ body=body, post_params=post_params,
313
+ _request_timeout=_request_timeout
314
+ )
315
+
316
+ except ApiException as e:
317
+ raise e
318
+
319
+ return response_data
320
+
321
+ def response_deserialize(
322
+ self,
323
+ response_data: rest.RESTResponse,
324
+ response_types_map: Optional[Dict[str, ApiResponseT]]=None
325
+ ) -> ApiResponse[ApiResponseT]:
326
+ """Deserializes response into an object.
327
+ :param response_data: RESTResponse object to be deserialized.
328
+ :param response_types_map: dict of response types.
329
+ :return: ApiResponse
330
+ """
331
+
332
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
333
+ assert response_data.data is not None, msg
334
+
335
+ response_type = response_types_map.get(str(response_data.status), None)
336
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
337
+ # if not found, look for '1XX', '2XX', etc.
338
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
339
+
340
+ # deserialize response data
341
+ response_text = None
342
+ return_data = None
343
+ try:
344
+ if response_type == "bytearray":
345
+ return_data = response_data.data
346
+ elif response_type == "file":
347
+ return_data = self.__deserialize_file(response_data)
348
+ elif response_type is not None:
349
+ match = None
350
+ content_type = response_data.getheader('content-type')
351
+ if content_type is not None:
352
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
353
+ encoding = match.group(1) if match else "utf-8"
354
+ response_text = response_data.data.decode(encoding)
355
+ return_data = self.deserialize(response_text, response_type, content_type)
356
+ finally:
357
+ if not 200 <= response_data.status <= 299:
358
+ raise ApiException.from_response(
359
+ http_resp=response_data,
360
+ body=response_text,
361
+ data=return_data,
362
+ )
363
+
364
+ return ApiResponse(
365
+ status_code = response_data.status,
366
+ data = return_data,
367
+ headers = response_data.getheaders(),
368
+ raw_data = response_data.data
369
+ )
370
+
371
+ def sanitize_for_serialization(self, obj):
372
+ """Builds a JSON POST object.
373
+
374
+ If obj is None, return None.
375
+ If obj is SecretStr, return obj.get_secret_value()
376
+ If obj is str, int, long, float, bool, return directly.
377
+ If obj is datetime.datetime, datetime.date
378
+ convert to string in iso8601 format.
379
+ If obj is decimal.Decimal return string representation.
380
+ If obj is list, sanitize each element in the list.
381
+ If obj is dict, return the dict.
382
+ If obj is OpenAPI model, return the properties dict.
383
+
384
+ :param obj: The data to serialize.
385
+ :return: The serialized form of data.
386
+ """
387
+ if obj is None:
388
+ return None
389
+ elif isinstance(obj, Enum):
390
+ return obj.value
391
+ elif isinstance(obj, SecretStr):
392
+ return obj.get_secret_value()
393
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
394
+ return obj
395
+ elif isinstance(obj, list):
396
+ return [
397
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
398
+ ]
399
+ elif isinstance(obj, tuple):
400
+ return tuple(
401
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
402
+ )
403
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
404
+ return obj.isoformat()
405
+ elif isinstance(obj, decimal.Decimal):
406
+ return str(obj)
407
+
408
+ elif isinstance(obj, dict):
409
+ obj_dict = obj
410
+ else:
411
+ # Convert model obj to dict except
412
+ # attributes `openapi_types`, `attribute_map`
413
+ # and attributes which value is not None.
414
+ # Convert attribute name to json key in
415
+ # model definition for request.
416
+ if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
417
+ obj_dict = obj.to_dict()
418
+ else:
419
+ obj_dict = obj.__dict__
420
+
421
+ return {
422
+ key: self.sanitize_for_serialization(val)
423
+ for key, val in obj_dict.items()
424
+ }
425
+
426
+ def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
427
+ """Deserializes response into an object.
428
+
429
+ :param response: RESTResponse object to be deserialized.
430
+ :param response_type: class literal for
431
+ deserialized object, or string of class name.
432
+ :param content_type: content type of response.
433
+
434
+ :return: deserialized object.
435
+ """
436
+
437
+ # fetch data from response object
438
+ if content_type is None:
439
+ try:
440
+ data = json.loads(response_text)
441
+ except ValueError:
442
+ data = response_text
443
+ elif re.match(r'^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE):
444
+ if response_text == "":
445
+ data = ""
446
+ else:
447
+ data = json.loads(response_text)
448
+ elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE):
449
+ data = response_text
450
+ else:
451
+ raise ApiException(
452
+ status=0,
453
+ reason="Unsupported content type: {0}".format(content_type)
454
+ )
455
+
456
+ return self.__deserialize(data, response_type)
457
+
458
+ def __deserialize(self, data, klass):
459
+ """Deserializes dict, list, str into an object.
460
+
461
+ :param data: dict, list or str.
462
+ :param klass: class literal, or string of class name.
463
+
464
+ :return: object.
465
+ """
466
+ if data is None:
467
+ return None
468
+
469
+ if isinstance(klass, str):
470
+ if klass.startswith('List['):
471
+ m = re.match(r'List\[(.*)]', klass)
472
+ assert m is not None, "Malformed List type definition"
473
+ sub_kls = m.group(1)
474
+ return [self.__deserialize(sub_data, sub_kls)
475
+ for sub_data in data]
476
+
477
+ if klass.startswith('Dict['):
478
+ m = re.match(r'Dict\[([^,]*), (.*)]', klass)
479
+ assert m is not None, "Malformed Dict type definition"
480
+ sub_kls = m.group(2)
481
+ return {k: self.__deserialize(v, sub_kls)
482
+ for k, v in data.items()}
483
+
484
+ # convert str to class
485
+ if klass in self.NATIVE_TYPES_MAPPING:
486
+ klass = self.NATIVE_TYPES_MAPPING[klass]
487
+ else:
488
+ klass = getattr(kalshi_python_async.models, klass)
489
+
490
+ if klass in self.PRIMITIVE_TYPES:
491
+ return self.__deserialize_primitive(data, klass)
492
+ elif klass == object:
493
+ return self.__deserialize_object(data)
494
+ elif klass == datetime.date:
495
+ return self.__deserialize_date(data)
496
+ elif klass == datetime.datetime:
497
+ return self.__deserialize_datetime(data)
498
+ elif klass == decimal.Decimal:
499
+ return decimal.Decimal(data)
500
+ elif issubclass(klass, Enum):
501
+ return self.__deserialize_enum(data, klass)
502
+ else:
503
+ return self.__deserialize_model(data, klass)
504
+
505
+ def parameters_to_tuples(self, params, collection_formats):
506
+ """Get parameters as list of tuples, formatting collections.
507
+
508
+ :param params: Parameters as dict or list of two-tuples
509
+ :param dict collection_formats: Parameter collection formats
510
+ :return: Parameters as list of tuples, collections formatted
511
+ """
512
+ new_params: List[Tuple[str, str]] = []
513
+ if collection_formats is None:
514
+ collection_formats = {}
515
+ for k, v in params.items() if isinstance(params, dict) else params:
516
+ if k in collection_formats:
517
+ collection_format = collection_formats[k]
518
+ if collection_format == 'multi':
519
+ new_params.extend((k, value) for value in v)
520
+ else:
521
+ if collection_format == 'ssv':
522
+ delimiter = ' '
523
+ elif collection_format == 'tsv':
524
+ delimiter = '\t'
525
+ elif collection_format == 'pipes':
526
+ delimiter = '|'
527
+ else: # csv is the default
528
+ delimiter = ','
529
+ new_params.append(
530
+ (k, delimiter.join(str(value) for value in v)))
531
+ else:
532
+ new_params.append((k, v))
533
+ return new_params
534
+
535
+ def parameters_to_url_query(self, params, collection_formats):
536
+ """Get parameters as list of tuples, formatting collections.
537
+
538
+ :param params: Parameters as dict or list of two-tuples
539
+ :param dict collection_formats: Parameter collection formats
540
+ :return: URL query string (e.g. a=Hello%20World&b=123)
541
+ """
542
+ new_params: List[Tuple[str, str]] = []
543
+ if collection_formats is None:
544
+ collection_formats = {}
545
+ for k, v in params.items() if isinstance(params, dict) else params:
546
+ if isinstance(v, bool):
547
+ v = str(v).lower()
548
+ if isinstance(v, (int, float)):
549
+ v = str(v)
550
+ if isinstance(v, dict):
551
+ v = json.dumps(v)
552
+
553
+ if k in collection_formats:
554
+ collection_format = collection_formats[k]
555
+ if collection_format == 'multi':
556
+ new_params.extend((k, quote(str(value))) for value in v)
557
+ else:
558
+ if collection_format == 'ssv':
559
+ delimiter = ' '
560
+ elif collection_format == 'tsv':
561
+ delimiter = '\t'
562
+ elif collection_format == 'pipes':
563
+ delimiter = '|'
564
+ else: # csv is the default
565
+ delimiter = ','
566
+ new_params.append(
567
+ (k, delimiter.join(quote(str(value)) for value in v))
568
+ )
569
+ else:
570
+ new_params.append((k, quote(str(v))))
571
+
572
+ return "&".join(["=".join(map(str, item)) for item in new_params])
573
+
574
+ def files_parameters(
575
+ self,
576
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
577
+ ):
578
+ """Builds form parameters.
579
+
580
+ :param files: File parameters.
581
+ :return: Form parameters with files.
582
+ """
583
+ params = []
584
+ for k, v in files.items():
585
+ if isinstance(v, str):
586
+ with open(v, 'rb') as f:
587
+ filename = os.path.basename(f.name)
588
+ filedata = f.read()
589
+ elif isinstance(v, bytes):
590
+ filename = k
591
+ filedata = v
592
+ elif isinstance(v, tuple):
593
+ filename, filedata = v
594
+ elif isinstance(v, list):
595
+ for file_param in v:
596
+ params.extend(self.files_parameters({k: file_param}))
597
+ continue
598
+ else:
599
+ raise ValueError("Unsupported file value")
600
+ mimetype = (
601
+ mimetypes.guess_type(filename)[0]
602
+ or 'application/octet-stream'
603
+ )
604
+ params.append(
605
+ tuple([k, tuple([filename, filedata, mimetype])])
606
+ )
607
+ return params
608
+
609
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
610
+ """Returns `Accept` based on an array of accepts provided.
611
+
612
+ :param accepts: List of headers.
613
+ :return: Accept (e.g. application/json).
614
+ """
615
+ if not accepts:
616
+ return None
617
+
618
+ for accept in accepts:
619
+ if re.search('json', accept, re.IGNORECASE):
620
+ return accept
621
+
622
+ return accepts[0]
623
+
624
+ def select_header_content_type(self, content_types):
625
+ """Returns `Content-Type` based on an array of content_types provided.
626
+
627
+ :param content_types: List of content-types.
628
+ :return: Content-Type (e.g. application/json).
629
+ """
630
+ if not content_types:
631
+ return None
632
+
633
+ for content_type in content_types:
634
+ if re.search('json', content_type, re.IGNORECASE):
635
+ return content_type
636
+
637
+ return content_types[0]
638
+
639
+ def update_params_for_auth(
640
+ self,
641
+ headers,
642
+ queries,
643
+ auth_settings,
644
+ resource_path,
645
+ method,
646
+ body,
647
+ request_auth=None
648
+ ) -> None:
649
+ """Updates header and query params based on authentication setting.
650
+
651
+ :param headers: Header parameters dict to be updated.
652
+ :param queries: Query parameters tuple list to be updated.
653
+ :param auth_settings: Authentication setting identifiers list.
654
+ :resource_path: A string representation of the HTTP request resource path.
655
+ :method: A string representation of the HTTP request method.
656
+ :body: A object representing the body of the HTTP request.
657
+ The object type is the return value of sanitize_for_serialization().
658
+ :param request_auth: if set, the provided settings will
659
+ override the token in the configuration.
660
+ """
661
+ if not auth_settings:
662
+ return
663
+
664
+ if request_auth:
665
+ self._apply_auth_params(
666
+ headers,
667
+ queries,
668
+ resource_path,
669
+ method,
670
+ body,
671
+ request_auth
672
+ )
673
+ else:
674
+ for auth in auth_settings:
675
+ auth_setting = self.configuration.auth_settings().get(auth)
676
+ if auth_setting:
677
+ self._apply_auth_params(
678
+ headers,
679
+ queries,
680
+ resource_path,
681
+ method,
682
+ body,
683
+ auth_setting
684
+ )
685
+
686
+ def _apply_auth_params(
687
+ self,
688
+ headers,
689
+ queries,
690
+ resource_path,
691
+ method,
692
+ body,
693
+ auth_setting
694
+ ) -> None:
695
+ """Updates the request parameters based on a single auth_setting
696
+
697
+ :param headers: Header parameters dict to be updated.
698
+ :param queries: Query parameters tuple list to be updated.
699
+ :resource_path: A string representation of the HTTP request resource path.
700
+ :method: A string representation of the HTTP request method.
701
+ :body: A object representing the body of the HTTP request.
702
+ The object type is the return value of sanitize_for_serialization().
703
+ :param auth_setting: auth settings for the endpoint
704
+ """
705
+ if auth_setting['in'] == 'cookie':
706
+ headers['Cookie'] = auth_setting['value']
707
+ elif auth_setting['in'] == 'header':
708
+ if auth_setting['type'] != 'http-signature':
709
+ headers[auth_setting['key']] = auth_setting['value']
710
+ elif auth_setting['in'] == 'query':
711
+ queries.append((auth_setting['key'], auth_setting['value']))
712
+ else:
713
+ raise ApiValueError(
714
+ 'Authentication token must be in `query` or `header`'
715
+ )
716
+
717
+ def __deserialize_file(self, response):
718
+ """Deserializes body to file
719
+
720
+ Saves response body into a file in a temporary folder,
721
+ using the filename from the `Content-Disposition` header if provided.
722
+
723
+ handle file downloading
724
+ save response body into a tmp file and return the instance
725
+
726
+ :param response: RESTResponse.
727
+ :return: file path.
728
+ """
729
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
730
+ os.close(fd)
731
+ os.remove(path)
732
+
733
+ content_disposition = response.getheader("Content-Disposition")
734
+ if content_disposition:
735
+ m = re.search(
736
+ r'filename=[\'"]?([^\'"\s]+)[\'"]?',
737
+ content_disposition
738
+ )
739
+ assert m is not None, "Unexpected 'content-disposition' header value"
740
+ filename = m.group(1)
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)