天择加密量化开放框架下载
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

744 lines
27 KiB

1 year ago
  1. # coding: utf-8
  2. """
  3. Gate API v4
  4. Welcome to Gate.io API APIv4 provides spot, margin and futures trading operations. There are public APIs to retrieve the real-time market statistics, and private APIs which needs authentication to trade on user's behalf. # noqa: E501
  5. Contact: support@mail.gate.io
  6. Generated by: https://openapi-generator.tech
  7. """
  8. from __future__ import absolute_import
  9. import atexit
  10. import datetime
  11. import hashlib
  12. import hmac
  13. import time
  14. from six.moves.urllib.parse import unquote_plus, urlencode, urlparse
  15. from dateutil.parser import parse
  16. import json
  17. import mimetypes
  18. from multiprocessing.pool import ThreadPool
  19. import os
  20. import re
  21. import tempfile
  22. # python 2 and python 3 compatibility library
  23. import six
  24. from six.moves.urllib.parse import quote
  25. from gate_api.configuration import Configuration
  26. import gate_api.models
  27. from gate_api import rest
  28. from gate_api.exceptions import ApiValueError, ApiException, GateApiException
  29. class ApiClient(object):
  30. """Generic API client for OpenAPI client library builds.
  31. OpenAPI generic API client. This client handles the client-
  32. server communication, and is invariant across implementations. Specifics of
  33. the methods and models for each application are generated from the OpenAPI
  34. templates.
  35. NOTE: This class is auto generated by OpenAPI Generator.
  36. Ref: https://openapi-generator.tech
  37. Do not edit the class manually.
  38. :param configuration: .Configuration object for this client
  39. :param header_name: a header to pass when making calls to the API.
  40. :param header_value: a header value to pass when making calls to
  41. the API.
  42. :param cookie: a cookie to include in the header when making calls
  43. to the API
  44. :param pool_threads: The number of threads to use for async requests
  45. to the API. More threads means more concurrent API requests.
  46. """
  47. PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
  48. NATIVE_TYPES_MAPPING = {
  49. 'int': int,
  50. 'long': int if six.PY3 else long, # noqa: F821
  51. 'float': float,
  52. 'str': str,
  53. 'bool': bool,
  54. 'date': datetime.date,
  55. 'datetime': datetime.datetime,
  56. 'object': object,
  57. }
  58. _pool = None
  59. def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1):
  60. if configuration is None:
  61. configuration = Configuration.get_default_copy()
  62. self.configuration = configuration
  63. self.pool_threads = pool_threads
  64. self.rest_client = rest.RESTClientObject(configuration)
  65. self.default_headers = {}
  66. if header_name is not None:
  67. self.default_headers[header_name] = header_value
  68. self.cookie = cookie
  69. # Set default User-Agent.
  70. self.user_agent = 'OpenAPI-Generator/4.42.0/python'
  71. self.client_side_validation = configuration.client_side_validation
  72. def __enter__(self):
  73. return self
  74. def __exit__(self, exc_type, exc_value, traceback):
  75. self.close()
  76. def close(self):
  77. if self._pool:
  78. self._pool.close()
  79. self._pool.join()
  80. self._pool = None
  81. if hasattr(atexit, 'unregister'):
  82. atexit.unregister(self.close)
  83. @property
  84. def pool(self):
  85. """Create thread pool on first request
  86. avoids instantiating unused threadpool for blocking clients.
  87. """
  88. if self._pool is None:
  89. atexit.register(self.close)
  90. self._pool = ThreadPool(self.pool_threads)
  91. return self._pool
  92. @property
  93. def user_agent(self):
  94. """User agent for this API client"""
  95. return self.default_headers['User-Agent']
  96. @user_agent.setter
  97. def user_agent(self, value):
  98. self.default_headers['User-Agent'] = value
  99. def set_default_header(self, header_name, header_value):
  100. self.default_headers[header_name] = header_value
  101. def __call_api(
  102. self,
  103. resource_path,
  104. method,
  105. path_params=None,
  106. query_params=None,
  107. header_params=None,
  108. body=None,
  109. post_params=None,
  110. files=None,
  111. response_type=None,
  112. auth_settings=None,
  113. _return_http_data_only=None,
  114. collection_formats=None,
  115. _preload_content=True,
  116. _request_timeout=None,
  117. _host=None,
  118. ):
  119. config = self.configuration
  120. # header parameters
  121. header_params = header_params or {}
  122. header_params.update(self.default_headers)
  123. if self.cookie:
  124. header_params['Cookie'] = self.cookie
  125. if header_params:
  126. header_params = self.sanitize_for_serialization(header_params)
  127. header_params = dict(self.parameters_to_tuples(header_params, collection_formats))
  128. # path parameters
  129. if path_params:
  130. path_params = self.sanitize_for_serialization(path_params)
  131. path_params = self.parameters_to_tuples(path_params, collection_formats)
  132. for k, v in path_params:
  133. # specified safe chars, encode everything
  134. resource_path = resource_path.replace('{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param))
  135. # query parameters
  136. if query_params:
  137. query_params = self.sanitize_for_serialization(query_params)
  138. query_params = self.parameters_to_tuples(query_params, collection_formats)
  139. # post parameters
  140. if post_params or files:
  141. post_params = post_params if post_params else []
  142. post_params = self.sanitize_for_serialization(post_params)
  143. post_params = self.parameters_to_tuples(post_params, collection_formats)
  144. post_params.extend(self.files_parameters(files))
  145. # body
  146. if body:
  147. body = self.sanitize_for_serialization(body)
  148. # request url
  149. if _host is None:
  150. url = self.configuration.host + resource_path
  151. else:
  152. # use server/host defined in path or operation instead
  153. url = _host + resource_path
  154. # auth setting
  155. self.update_params_for_auth(method, url, header_params, query_params, body, auth_settings)
  156. try:
  157. # perform request and return response
  158. response_data = self.request(
  159. method,
  160. url,
  161. query_params=query_params,
  162. headers=header_params,
  163. post_params=post_params,
  164. body=body,
  165. _preload_content=_preload_content,
  166. _request_timeout=_request_timeout,
  167. )
  168. except ApiException as e:
  169. e.body = e.body.decode('utf-8') if six.PY3 else e.body
  170. try:
  171. err = json.loads(e.body)
  172. except ValueError:
  173. raise e
  174. else:
  175. if not err.get('label'):
  176. raise e
  177. raise GateApiException(err.get('label'), err.get('message'), err.get('detail'), e)
  178. content_type = response_data.getheader('content-type')
  179. self.last_response = response_data
  180. return_data = response_data
  181. if not _preload_content:
  182. return return_data
  183. if six.PY3 and response_type not in ["file", "bytes"]:
  184. match = None
  185. if content_type is not None:
  186. match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
  187. encoding = match.group(1) if match else "utf-8"
  188. response_data.data = response_data.data.decode(encoding)
  189. # deserialize response data
  190. if response_type:
  191. return_data = self.deserialize(response_data, response_type)
  192. else:
  193. return_data = None
  194. if _return_http_data_only:
  195. return return_data
  196. else:
  197. return (return_data, response_data.status, response_data.getheaders())
  198. def sanitize_for_serialization(self, obj):
  199. """Builds a JSON POST object.
  200. If obj is None, return None.
  201. If obj is str, int, long, float, bool, return directly.
  202. If obj is datetime.datetime, datetime.date
  203. convert to string in iso8601 format.
  204. If obj is list, sanitize each element in the list.
  205. If obj is dict, return the dict.
  206. If obj is OpenAPI model, return the properties dict.
  207. :param obj: The data to serialize.
  208. :return: The serialized form of data.
  209. """
  210. if obj is None:
  211. return None
  212. elif isinstance(obj, self.PRIMITIVE_TYPES):
  213. return obj
  214. elif isinstance(obj, list):
  215. return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
  216. elif isinstance(obj, tuple):
  217. return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj)
  218. elif isinstance(obj, (datetime.datetime, datetime.date)):
  219. return obj.isoformat()
  220. if isinstance(obj, dict):
  221. obj_dict = obj
  222. else:
  223. # Convert model obj to dict except
  224. # attributes `openapi_types`, `attribute_map`
  225. # and attributes which value is not None.
  226. # Convert attribute name to json key in
  227. # model definition for request.
  228. obj_dict = {
  229. obj.attribute_map[attr]: getattr(obj, attr)
  230. for attr, _ in six.iteritems(obj.openapi_types)
  231. if getattr(obj, attr) is not None
  232. }
  233. return {key: self.sanitize_for_serialization(val) for key, val in six.iteritems(obj_dict)}
  234. def deserialize(self, response, response_type):
  235. """Deserializes response into an object.
  236. :param response: RESTResponse object to be deserialized.
  237. :param response_type: class literal for
  238. deserialized object, or string of class name.
  239. :return: deserialized object.
  240. """
  241. # handle file downloading
  242. # save response body into a tmp file and return the instance
  243. if response_type == "file":
  244. return self.__deserialize_file(response)
  245. # fetch data from response object
  246. try:
  247. data = json.loads(response.data)
  248. except ValueError:
  249. data = response.data
  250. return self.__deserialize(data, response_type)
  251. def __deserialize(self, data, klass):
  252. """Deserializes dict, list, str into an object.
  253. :param data: dict, list or str.
  254. :param klass: class literal, or string of class name.
  255. :return: object.
  256. """
  257. if data is None:
  258. return None
  259. if type(klass) == str:
  260. if klass.startswith('list['):
  261. sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
  262. return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
  263. if klass.startswith('dict('):
  264. sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2)
  265. return {k: self.__deserialize(v, sub_kls) for k, v in six.iteritems(data)}
  266. # convert str to class
  267. if klass in self.NATIVE_TYPES_MAPPING:
  268. klass = self.NATIVE_TYPES_MAPPING[klass]
  269. else:
  270. klass = getattr(gate_api.models, klass)
  271. if klass in self.PRIMITIVE_TYPES:
  272. return self.__deserialize_primitive(data, klass)
  273. elif klass == object:
  274. return self.__deserialize_object(data)
  275. elif klass == datetime.date:
  276. return self.__deserialize_date(data)
  277. elif klass == datetime.datetime:
  278. return self.__deserialize_datetime(data)
  279. else:
  280. return self.__deserialize_model(data, klass)
  281. def call_api(
  282. self,
  283. resource_path,
  284. method,
  285. path_params=None,
  286. query_params=None,
  287. header_params=None,
  288. body=None,
  289. post_params=None,
  290. files=None,
  291. response_type=None,
  292. auth_settings=None,
  293. async_req=None,
  294. _return_http_data_only=None,
  295. collection_formats=None,
  296. _preload_content=True,
  297. _request_timeout=None,
  298. _host=None,
  299. ):
  300. """Makes the HTTP request (synchronous) and returns deserialized data.
  301. To make an async_req request, set the async_req parameter.
  302. :param resource_path: Path to method endpoint.
  303. :param method: Method to call.
  304. :param path_params: Path parameters in the url.
  305. :param query_params: Query parameters in the url.
  306. :param header_params: Header parameters to be
  307. placed in the request header.
  308. :param body: Request body.
  309. :param list post_params: Request post form parameters,
  310. for `application/x-www-form-urlencoded`, `multipart/form-data`.
  311. :param list auth_settings: Auth Settings names for the request.
  312. :param response_type: Response data type.
  313. :param dict files: key -> filename, value -> filepath,
  314. for `multipart/form-data`.
  315. :param bool async_req: execute request asynchronously
  316. :param _return_http_data_only: response data without head status code
  317. and headers
  318. :param collection_formats: dict of collection formats for path, query,
  319. header, and post parameters.
  320. :param _preload_content: if False, the urllib3.HTTPResponse object will
  321. be returned without reading/decoding response
  322. data. Default is True.
  323. :param _request_timeout: timeout setting for this request. If one
  324. number provided, it will be total request
  325. timeout. It can also be a pair (tuple) of
  326. (connection, read) timeouts.
  327. :param _host: server/host defined in path or operation instead
  328. :return:
  329. If async_req parameter is True,
  330. the request will be called asynchronously.
  331. The method will return the request thread.
  332. If parameter async_req is False or missing,
  333. then the method will return the response directly.
  334. """
  335. if not async_req:
  336. return self.__call_api(
  337. resource_path,
  338. method,
  339. path_params,
  340. query_params,
  341. header_params,
  342. body,
  343. post_params,
  344. files,
  345. response_type,
  346. auth_settings,
  347. _return_http_data_only,
  348. collection_formats,
  349. _preload_content,
  350. _request_timeout,
  351. _host,
  352. )
  353. return self.pool.apply_async(
  354. self.__call_api,
  355. (
  356. resource_path,
  357. method,
  358. path_params,
  359. query_params,
  360. header_params,
  361. body,
  362. post_params,
  363. files,
  364. response_type,
  365. auth_settings,
  366. _return_http_data_only,
  367. collection_formats,
  368. _preload_content,
  369. _request_timeout,
  370. _host,
  371. ),
  372. )
  373. def request(
  374. self,
  375. method,
  376. url,
  377. query_params=None,
  378. headers=None,
  379. post_params=None,
  380. body=None,
  381. _preload_content=True,
  382. _request_timeout=None,
  383. ):
  384. """Makes the HTTP request using RESTClient."""
  385. if method == "GET":
  386. return self.rest_client.GET(
  387. url,
  388. query_params=query_params,
  389. _preload_content=_preload_content,
  390. _request_timeout=_request_timeout,
  391. headers=headers,
  392. )
  393. elif method == "HEAD":
  394. return self.rest_client.HEAD(
  395. url,
  396. query_params=query_params,
  397. _preload_content=_preload_content,
  398. _request_timeout=_request_timeout,
  399. headers=headers,
  400. )
  401. elif method == "OPTIONS":
  402. return self.rest_client.OPTIONS(
  403. url,
  404. query_params=query_params,
  405. headers=headers,
  406. _preload_content=_preload_content,
  407. _request_timeout=_request_timeout,
  408. )
  409. elif method == "POST":
  410. return self.rest_client.POST(
  411. url,
  412. query_params=query_params,
  413. headers=headers,
  414. post_params=post_params,
  415. _preload_content=_preload_content,
  416. _request_timeout=_request_timeout,
  417. body=body,
  418. )
  419. elif method == "PUT":
  420. return self.rest_client.PUT(
  421. url,
  422. query_params=query_params,
  423. headers=headers,
  424. post_params=post_params,
  425. _preload_content=_preload_content,
  426. _request_timeout=_request_timeout,
  427. body=body,
  428. )
  429. elif method == "PATCH":
  430. return self.rest_client.PATCH(
  431. url,
  432. query_params=query_params,
  433. headers=headers,
  434. post_params=post_params,
  435. _preload_content=_preload_content,
  436. _request_timeout=_request_timeout,
  437. body=body,
  438. )
  439. elif method == "DELETE":
  440. return self.rest_client.DELETE(
  441. url,
  442. query_params=query_params,
  443. headers=headers,
  444. _preload_content=_preload_content,
  445. _request_timeout=_request_timeout,
  446. body=body,
  447. )
  448. else:
  449. raise ApiValueError("http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`.")
  450. def parameters_to_tuples(self, params, collection_formats):
  451. """Get parameters as list of tuples, formatting collections.
  452. :param params: Parameters as dict or list of two-tuples
  453. :param dict collection_formats: Parameter collection formats
  454. :return: Parameters as list of tuples, collections formatted
  455. """
  456. new_params = []
  457. if collection_formats is None:
  458. collection_formats = {}
  459. for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
  460. if k in collection_formats:
  461. collection_format = collection_formats[k]
  462. if collection_format == 'multi':
  463. new_params.extend((k, value) for value in v)
  464. else:
  465. if collection_format == 'ssv':
  466. delimiter = ' '
  467. elif collection_format == 'tsv':
  468. delimiter = '\t'
  469. elif collection_format == 'pipes':
  470. delimiter = '|'
  471. else: # csv is the default
  472. delimiter = ','
  473. new_params.append((k, delimiter.join(str(value) for value in v)))
  474. else:
  475. new_params.append((k, v))
  476. return new_params
  477. def files_parameters(self, files=None):
  478. """Builds form parameters.
  479. :param files: File parameters.
  480. :return: Form parameters with files.
  481. """
  482. params = []
  483. if files:
  484. for k, v in six.iteritems(files):
  485. if not v:
  486. continue
  487. file_names = v if type(v) is list else [v]
  488. for n in file_names:
  489. with open(n, 'rb') as f:
  490. filename = os.path.basename(f.name)
  491. filedata = f.read()
  492. mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  493. params.append(tuple([k, tuple([filename, filedata, mimetype])]))
  494. return params
  495. def select_header_accept(self, accepts):
  496. """Returns `Accept` based on an array of accepts provided.
  497. :param accepts: List of headers.
  498. :return: Accept (e.g. application/json).
  499. """
  500. if not accepts:
  501. return
  502. accepts = [x.lower() for x in accepts]
  503. if 'application/json' in accepts:
  504. return 'application/json'
  505. else:
  506. return ', '.join(accepts)
  507. def select_header_content_type(self, content_types):
  508. """Returns `Content-Type` based on an array of content_types provided.
  509. :param content_types: List of content-types.
  510. :return: Content-Type (e.g. application/json).
  511. """
  512. if not content_types:
  513. return 'application/json'
  514. content_types = [x.lower() for x in content_types]
  515. if 'application/json' in content_types or '*/*' in content_types:
  516. return 'application/json'
  517. else:
  518. return content_types[0]
  519. def update_params_for_auth(self, method, url, headers, querys, body, auth_settings):
  520. """Updates header and query params based on authentication setting.
  521. :param method: Request method
  522. :param url: Request path, host included
  523. :param headers: Header parameters dict to be updated.
  524. :param querys: Query parameters tuple list to be updated.
  525. :param body: Request body
  526. :param auth_settings: Authentication setting identifiers list.
  527. """
  528. if not auth_settings:
  529. return
  530. for auth in auth_settings:
  531. auth_setting = self.configuration.auth_settings().get(auth)
  532. if auth_setting:
  533. if auth_setting['type'] == 'apiv4':
  534. auth_headers = self.gen_sign(method, urlparse(url).path, unquote_plus(urlencode(querys)), body)
  535. headers.update(auth_headers)
  536. continue
  537. if auth_setting['in'] == 'cookie':
  538. headers['Cookie'] = auth_setting['value']
  539. elif auth_setting['in'] == 'header':
  540. headers[auth_setting['key']] = auth_setting['value']
  541. elif auth_setting['in'] == 'query':
  542. querys.append((auth_setting['key'], auth_setting['value']))
  543. else:
  544. raise ApiValueError('Authentication token must be in `query` or `header`')
  545. def gen_sign(self, method, url, query_string=None, body=None):
  546. """generate authentication headers
  547. :param method: http request method
  548. :param url: http resource path
  549. :param query_string: query string
  550. :param body: request body
  551. :return: signature headers
  552. """
  553. t = time.time()
  554. m = hashlib.sha512()
  555. if body is not None:
  556. if not isinstance(body, six.string_types):
  557. body = json.dumps(body)
  558. m.update(body.encode('utf-8'))
  559. hashed_payload = m.hexdigest()
  560. s = '%s\n%s\n%s\n%s\n%s' % (method, url, query_string or "", hashed_payload, t)
  561. sign = hmac.new(self.configuration.secret.encode('utf-8'), s.encode('utf-8'), hashlib.sha512).hexdigest()
  562. return {'KEY': self.configuration.key, 'Timestamp': str(t), 'SIGN': sign}
  563. def __deserialize_file(self, response):
  564. """Deserializes body to file
  565. Saves response body into a file in a temporary folder,
  566. using the filename from the `Content-Disposition` header if provided.
  567. :param response: RESTResponse.
  568. :return: file path.
  569. """
  570. fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
  571. os.close(fd)
  572. os.remove(path)
  573. content_disposition = response.getheader("Content-Disposition")
  574. if content_disposition:
  575. filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1)
  576. path = os.path.join(os.path.dirname(path), filename)
  577. with open(path, "wb") as f:
  578. f.write(response.data)
  579. return path
  580. def __deserialize_primitive(self, data, klass):
  581. """Deserializes string to primitive type.
  582. :param data: str.
  583. :param klass: class literal.
  584. :return: int, long, float, str, bool.
  585. """
  586. try:
  587. return klass(data)
  588. except UnicodeEncodeError:
  589. return six.text_type(data)
  590. except TypeError:
  591. return data
  592. def __deserialize_object(self, value):
  593. """Return an original value.
  594. :return: object.
  595. """
  596. return value
  597. def __deserialize_date(self, string):
  598. """Deserializes string to date.
  599. :param string: str.
  600. :return: date.
  601. """
  602. try:
  603. return parse(string).date()
  604. except ImportError:
  605. return string
  606. except ValueError:
  607. raise rest.ApiException(status=0, reason="Failed to parse `{0}` as date object".format(string))
  608. def __deserialize_datetime(self, string):
  609. """Deserializes string to datetime.
  610. The string should be in iso8601 datetime format.
  611. :param string: str.
  612. :return: datetime.
  613. """
  614. try:
  615. return parse(string)
  616. except ImportError:
  617. return string
  618. except ValueError:
  619. raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as datetime object".format(string)))
  620. def __deserialize_model(self, data, klass):
  621. """Deserializes list or dict to model.
  622. :param data: dict, list.
  623. :param klass: class literal.
  624. :return: model object.
  625. """
  626. has_discriminator = False
  627. if hasattr(klass, 'get_real_child_model') and klass.discriminator_value_class_map:
  628. has_discriminator = True
  629. if not klass.openapi_types and has_discriminator is False:
  630. return data
  631. kwargs = {}
  632. if data is not None and klass.openapi_types is not None and isinstance(data, (list, dict)):
  633. for attr, attr_type in six.iteritems(klass.openapi_types):
  634. if klass.attribute_map[attr] in data:
  635. value = data[klass.attribute_map[attr]]
  636. kwargs[attr] = self.__deserialize(value, attr_type)
  637. instance = klass(**kwargs)
  638. if has_discriminator:
  639. klass_name = instance.get_real_child_model(data)
  640. if klass_name:
  641. instance = self.__deserialize(data, klass_name)
  642. return instance