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