lighter-sdk 0.1.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (125) hide show
  1. lighter/__init__.py +140 -0
  2. lighter/api/__init__.py +11 -0
  3. lighter/api/account_api.py +2371 -0
  4. lighter/api/block_api.py +863 -0
  5. lighter/api/candlestick_api.py +718 -0
  6. lighter/api/info_api.py +282 -0
  7. lighter/api/order_api.py +2734 -0
  8. lighter/api/root_api.py +529 -0
  9. lighter/api/transaction_api.py +3525 -0
  10. lighter/api_client.py +784 -0
  11. lighter/api_response.py +21 -0
  12. lighter/configuration.py +475 -0
  13. lighter/exceptions.py +199 -0
  14. lighter/models/__init__.py +112 -0
  15. lighter/models/account.py +110 -0
  16. lighter/models/account_api_keys.py +104 -0
  17. lighter/models/account_market_stats.py +98 -0
  18. lighter/models/account_metadata.py +94 -0
  19. lighter/models/account_pn_l.py +106 -0
  20. lighter/models/account_position.py +112 -0
  21. lighter/models/account_stats.py +102 -0
  22. lighter/models/accounts.py +106 -0
  23. lighter/models/api_key.py +98 -0
  24. lighter/models/block.py +124 -0
  25. lighter/models/blocks.py +106 -0
  26. lighter/models/bridge_supported_network.py +96 -0
  27. lighter/models/candlestick.py +106 -0
  28. lighter/models/candlesticks.py +106 -0
  29. lighter/models/contract_address.py +94 -0
  30. lighter/models/current_height.py +96 -0
  31. lighter/models/cursor.py +92 -0
  32. lighter/models/deposit_history.py +106 -0
  33. lighter/models/deposit_history_item.py +105 -0
  34. lighter/models/detailed_account.py +152 -0
  35. lighter/models/detailed_accounts.py +106 -0
  36. lighter/models/detailed_candlestick.py +108 -0
  37. lighter/models/enriched_tx.py +129 -0
  38. lighter/models/exchange_stats.py +110 -0
  39. lighter/models/fee_bucket.py +96 -0
  40. lighter/models/funding.py +98 -0
  41. lighter/models/fundings.py +106 -0
  42. lighter/models/is_whitelisted.py +98 -0
  43. lighter/models/l1_provider_info.py +98 -0
  44. lighter/models/layer2_basic_info.py +100 -0
  45. lighter/models/liquidation.py +100 -0
  46. lighter/models/market_info.py +116 -0
  47. lighter/models/next_nonce.py +96 -0
  48. lighter/models/order.py +159 -0
  49. lighter/models/order_book.py +119 -0
  50. lighter/models/order_book_depth.py +115 -0
  51. lighter/models/order_book_detail.py +151 -0
  52. lighter/models/order_book_details.py +104 -0
  53. lighter/models/order_book_orders.py +117 -0
  54. lighter/models/order_book_stats.py +102 -0
  55. lighter/models/order_books.py +104 -0
  56. lighter/models/orders.py +106 -0
  57. lighter/models/pn_l_entry.py +94 -0
  58. lighter/models/position_funding.py +111 -0
  59. lighter/models/price_level.py +94 -0
  60. lighter/models/public_pool.py +128 -0
  61. lighter/models/public_pool_info.py +100 -0
  62. lighter/models/public_pool_share.py +96 -0
  63. lighter/models/public_pools.py +106 -0
  64. lighter/models/req_get_account.py +101 -0
  65. lighter/models/req_get_account_active_orders.py +96 -0
  66. lighter/models/req_get_account_api_keys.py +94 -0
  67. lighter/models/req_get_account_by_l1_address.py +92 -0
  68. lighter/models/req_get_account_inactive_orders.py +103 -0
  69. lighter/models/req_get_account_orders.py +99 -0
  70. lighter/models/req_get_account_pending_txs.py +106 -0
  71. lighter/models/req_get_account_pn_l.py +118 -0
  72. lighter/models/req_get_account_txs.py +111 -0
  73. lighter/models/req_get_block.py +101 -0
  74. lighter/models/req_get_block_txs.py +101 -0
  75. lighter/models/req_get_by_account.py +101 -0
  76. lighter/models/req_get_candlesticks.py +109 -0
  77. lighter/models/req_get_deposit_history.py +106 -0
  78. lighter/models/req_get_fee_bucket.py +92 -0
  79. lighter/models/req_get_fundings.py +107 -0
  80. lighter/models/req_get_l1_tx.py +92 -0
  81. lighter/models/req_get_latest_deposit.py +92 -0
  82. lighter/models/req_get_next_nonce.py +94 -0
  83. lighter/models/req_get_order_book_details.py +92 -0
  84. lighter/models/req_get_order_book_orders.py +95 -0
  85. lighter/models/req_get_order_books.py +92 -0
  86. lighter/models/req_get_public_pools.py +109 -0
  87. lighter/models/req_get_range_with_cursor.py +95 -0
  88. lighter/models/req_get_range_with_index.py +95 -0
  89. lighter/models/req_get_range_with_index_sortable.py +107 -0
  90. lighter/models/req_get_recent_trades.py +95 -0
  91. lighter/models/req_get_trades.py +126 -0
  92. lighter/models/req_get_tx.py +101 -0
  93. lighter/models/req_get_withdraw_history.py +106 -0
  94. lighter/models/req_is_whitelisted.py +92 -0
  95. lighter/models/result_code.py +94 -0
  96. lighter/models/simple_order.py +102 -0
  97. lighter/models/status.py +94 -0
  98. lighter/models/sub_accounts.py +106 -0
  99. lighter/models/ticker.py +103 -0
  100. lighter/models/trade.py +125 -0
  101. lighter/models/trades.py +106 -0
  102. lighter/models/tx.py +121 -0
  103. lighter/models/tx_hash.py +96 -0
  104. lighter/models/tx_hashes.py +96 -0
  105. lighter/models/txs.py +104 -0
  106. lighter/models/validator_info.py +94 -0
  107. lighter/models/withdraw_history.py +110 -0
  108. lighter/models/withdraw_history_cursor.py +94 -0
  109. lighter/models/withdraw_history_item.py +114 -0
  110. lighter/models/zk_lighter_info.py +92 -0
  111. lighter/py.typed +0 -0
  112. lighter/rest.py +215 -0
  113. lighter/signer_client.py +440 -0
  114. lighter/signers/signer-amd64.so +0 -0
  115. lighter/signers/signer-arm64.dylib +0 -0
  116. lighter/transactions/__init__.py +3 -0
  117. lighter/transactions/cancel_order.py +27 -0
  118. lighter/transactions/create_order.py +33 -0
  119. lighter/transactions/withdraw.py +25 -0
  120. lighter/ws_client.py +160 -0
  121. lighter_sdk-0.1.0.dist-info/LICENSE +201 -0
  122. lighter_sdk-0.1.0.dist-info/METADATA +26 -0
  123. lighter_sdk-0.1.0.dist-info/RECORD +125 -0
  124. lighter_sdk-0.1.0.dist-info/WHEEL +5 -0
  125. lighter_sdk-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,110 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+
5
+
6
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
7
+
8
+ The version of the OpenAPI document:
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ from __future__ import annotations
16
+ import pprint
17
+ import re # noqa: F401
18
+ import json
19
+
20
+ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr
21
+ from typing import Any, ClassVar, Dict, List, Optional
22
+ from lighter.models.withdraw_history_cursor import WithdrawHistoryCursor
23
+ from lighter.models.withdraw_history_item import WithdrawHistoryItem
24
+ from typing import Optional, Set
25
+ from typing_extensions import Self
26
+
27
+ class WithdrawHistory(BaseModel):
28
+ """
29
+ WithdrawHistory
30
+ """ # noqa: E501
31
+ code: StrictInt
32
+ message: Optional[StrictStr] = None
33
+ withdraws: List[WithdrawHistoryItem]
34
+ cursor: WithdrawHistoryCursor
35
+ __properties: ClassVar[List[str]] = ["code", "message", "withdraws", "cursor"]
36
+
37
+ model_config = ConfigDict(
38
+ populate_by_name=True,
39
+ validate_assignment=True,
40
+ protected_namespaces=(),
41
+ )
42
+
43
+
44
+ def to_str(self) -> str:
45
+ """Returns the string representation of the model using alias"""
46
+ return pprint.pformat(self.model_dump(by_alias=True))
47
+
48
+ def to_json(self) -> str:
49
+ """Returns the JSON representation of the model using alias"""
50
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
51
+ return json.dumps(self.to_dict())
52
+
53
+ @classmethod
54
+ def from_json(cls, json_str: str) -> Optional[Self]:
55
+ """Create an instance of WithdrawHistory from a JSON string"""
56
+ return cls.from_dict(json.loads(json_str))
57
+
58
+ def to_dict(self) -> Dict[str, Any]:
59
+ """Return the dictionary representation of the model using alias.
60
+
61
+ This has the following differences from calling pydantic's
62
+ `self.model_dump(by_alias=True)`:
63
+
64
+ * `None` is only added to the output dict for nullable fields that
65
+ were set at model initialization. Other fields with value `None`
66
+ are ignored.
67
+ """
68
+ excluded_fields: Set[str] = set([
69
+ ])
70
+
71
+ _dict = self.model_dump(
72
+ by_alias=True,
73
+ exclude=excluded_fields,
74
+ exclude_none=True,
75
+ )
76
+ # override the default output from pydantic by calling `to_dict()` of each item in withdraws (list)
77
+ _items = []
78
+ if self.withdraws:
79
+ for _item in self.withdraws:
80
+ if _item:
81
+ _items.append(_item.to_dict())
82
+ _dict['withdraws'] = _items
83
+ # override the default output from pydantic by calling `to_dict()` of cursor
84
+ if self.cursor:
85
+ _dict['cursor'] = self.cursor.to_dict()
86
+ return _dict
87
+
88
+ @classmethod
89
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
90
+ """Create an instance of WithdrawHistory from a dict"""
91
+ if obj is None:
92
+ return None
93
+
94
+ if not isinstance(obj, dict):
95
+ return cls.model_validate(obj)
96
+
97
+ # raise errors for additional fields in the input
98
+ for _key in obj.keys():
99
+ if _key not in cls.__properties:
100
+ raise ValueError("Error due to additional fields (not defined in WithdrawHistory) in the input: " + _key)
101
+
102
+ _obj = cls.model_validate({
103
+ "code": obj.get("code"),
104
+ "message": obj.get("message"),
105
+ "withdraws": [WithdrawHistoryItem.from_dict(_item) for _item in obj["withdraws"]] if obj.get("withdraws") is not None else None,
106
+ "cursor": WithdrawHistoryCursor.from_dict(obj["cursor"]) if obj.get("cursor") is not None else None
107
+ })
108
+ return _obj
109
+
110
+
@@ -0,0 +1,94 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+
5
+
6
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
7
+
8
+ The version of the OpenAPI document:
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ from __future__ import annotations
16
+ import pprint
17
+ import re # noqa: F401
18
+ import json
19
+
20
+ from pydantic import BaseModel, ConfigDict, StrictStr
21
+ from typing import Any, ClassVar, Dict, List
22
+ from typing import Optional, Set
23
+ from typing_extensions import Self
24
+
25
+ class WithdrawHistoryCursor(BaseModel):
26
+ """
27
+ WithdrawHistoryCursor
28
+ """ # noqa: E501
29
+ secure_id: StrictStr
30
+ fast_id: StrictStr
31
+ __properties: ClassVar[List[str]] = ["secure_id", "fast_id"]
32
+
33
+ model_config = ConfigDict(
34
+ populate_by_name=True,
35
+ validate_assignment=True,
36
+ protected_namespaces=(),
37
+ )
38
+
39
+
40
+ def to_str(self) -> str:
41
+ """Returns the string representation of the model using alias"""
42
+ return pprint.pformat(self.model_dump(by_alias=True))
43
+
44
+ def to_json(self) -> str:
45
+ """Returns the JSON representation of the model using alias"""
46
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
47
+ return json.dumps(self.to_dict())
48
+
49
+ @classmethod
50
+ def from_json(cls, json_str: str) -> Optional[Self]:
51
+ """Create an instance of WithdrawHistoryCursor from a JSON string"""
52
+ return cls.from_dict(json.loads(json_str))
53
+
54
+ def to_dict(self) -> Dict[str, Any]:
55
+ """Return the dictionary representation of the model using alias.
56
+
57
+ This has the following differences from calling pydantic's
58
+ `self.model_dump(by_alias=True)`:
59
+
60
+ * `None` is only added to the output dict for nullable fields that
61
+ were set at model initialization. Other fields with value `None`
62
+ are ignored.
63
+ """
64
+ excluded_fields: Set[str] = set([
65
+ ])
66
+
67
+ _dict = self.model_dump(
68
+ by_alias=True,
69
+ exclude=excluded_fields,
70
+ exclude_none=True,
71
+ )
72
+ return _dict
73
+
74
+ @classmethod
75
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
76
+ """Create an instance of WithdrawHistoryCursor from a dict"""
77
+ if obj is None:
78
+ return None
79
+
80
+ if not isinstance(obj, dict):
81
+ return cls.model_validate(obj)
82
+
83
+ # raise errors for additional fields in the input
84
+ for _key in obj.keys():
85
+ if _key not in cls.__properties:
86
+ raise ValueError("Error due to additional fields (not defined in WithdrawHistoryCursor) in the input: " + _key)
87
+
88
+ _obj = cls.model_validate({
89
+ "secure_id": obj.get("secure_id"),
90
+ "fast_id": obj.get("fast_id")
91
+ })
92
+ return _obj
93
+
94
+
@@ -0,0 +1,114 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+
5
+
6
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
7
+
8
+ The version of the OpenAPI document:
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ from __future__ import annotations
16
+ import pprint
17
+ import re # noqa: F401
18
+ import json
19
+
20
+ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr, field_validator
21
+ from typing import Any, ClassVar, Dict, List
22
+ from typing import Optional, Set
23
+ from typing_extensions import Self
24
+
25
+ class WithdrawHistoryItem(BaseModel):
26
+ """
27
+ WithdrawHistoryItem
28
+ """ # noqa: E501
29
+ id: StrictStr
30
+ amount: StrictStr
31
+ timestamp: StrictInt
32
+ status: StrictStr
33
+ type: StrictStr
34
+ __properties: ClassVar[List[str]] = ["id", "amount", "timestamp", "status", "type"]
35
+
36
+ @field_validator('status')
37
+ def status_validate_enum(cls, value):
38
+ """Validates the enum"""
39
+ if value not in set(['failed', 'pending', 'claimable', 'refunded', 'completed']):
40
+ raise ValueError("must be one of enum values ('failed', 'pending', 'claimable', 'refunded', 'completed')")
41
+ return value
42
+
43
+ @field_validator('type')
44
+ def type_validate_enum(cls, value):
45
+ """Validates the enum"""
46
+ if value not in set(['secure', 'fast']):
47
+ raise ValueError("must be one of enum values ('secure', 'fast')")
48
+ return value
49
+
50
+ model_config = ConfigDict(
51
+ populate_by_name=True,
52
+ validate_assignment=True,
53
+ protected_namespaces=(),
54
+ )
55
+
56
+
57
+ def to_str(self) -> str:
58
+ """Returns the string representation of the model using alias"""
59
+ return pprint.pformat(self.model_dump(by_alias=True))
60
+
61
+ def to_json(self) -> str:
62
+ """Returns the JSON representation of the model using alias"""
63
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
64
+ return json.dumps(self.to_dict())
65
+
66
+ @classmethod
67
+ def from_json(cls, json_str: str) -> Optional[Self]:
68
+ """Create an instance of WithdrawHistoryItem from a JSON string"""
69
+ return cls.from_dict(json.loads(json_str))
70
+
71
+ def to_dict(self) -> Dict[str, Any]:
72
+ """Return the dictionary representation of the model using alias.
73
+
74
+ This has the following differences from calling pydantic's
75
+ `self.model_dump(by_alias=True)`:
76
+
77
+ * `None` is only added to the output dict for nullable fields that
78
+ were set at model initialization. Other fields with value `None`
79
+ are ignored.
80
+ """
81
+ excluded_fields: Set[str] = set([
82
+ ])
83
+
84
+ _dict = self.model_dump(
85
+ by_alias=True,
86
+ exclude=excluded_fields,
87
+ exclude_none=True,
88
+ )
89
+ return _dict
90
+
91
+ @classmethod
92
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
93
+ """Create an instance of WithdrawHistoryItem from a dict"""
94
+ if obj is None:
95
+ return None
96
+
97
+ if not isinstance(obj, dict):
98
+ return cls.model_validate(obj)
99
+
100
+ # raise errors for additional fields in the input
101
+ for _key in obj.keys():
102
+ if _key not in cls.__properties:
103
+ raise ValueError("Error due to additional fields (not defined in WithdrawHistoryItem) in the input: " + _key)
104
+
105
+ _obj = cls.model_validate({
106
+ "id": obj.get("id"),
107
+ "amount": obj.get("amount"),
108
+ "timestamp": obj.get("timestamp"),
109
+ "status": obj.get("status"),
110
+ "type": obj.get("type")
111
+ })
112
+ return _obj
113
+
114
+
@@ -0,0 +1,92 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+
5
+
6
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
7
+
8
+ The version of the OpenAPI document:
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ from __future__ import annotations
16
+ import pprint
17
+ import re # noqa: F401
18
+ import json
19
+
20
+ from pydantic import BaseModel, ConfigDict, StrictStr
21
+ from typing import Any, ClassVar, Dict, List
22
+ from typing import Optional, Set
23
+ from typing_extensions import Self
24
+
25
+ class ZkLighterInfo(BaseModel):
26
+ """
27
+ ZkLighterInfo
28
+ """ # noqa: E501
29
+ contract_address: StrictStr
30
+ __properties: ClassVar[List[str]] = ["contract_address"]
31
+
32
+ model_config = ConfigDict(
33
+ populate_by_name=True,
34
+ validate_assignment=True,
35
+ protected_namespaces=(),
36
+ )
37
+
38
+
39
+ def to_str(self) -> str:
40
+ """Returns the string representation of the model using alias"""
41
+ return pprint.pformat(self.model_dump(by_alias=True))
42
+
43
+ def to_json(self) -> str:
44
+ """Returns the JSON representation of the model using alias"""
45
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
46
+ return json.dumps(self.to_dict())
47
+
48
+ @classmethod
49
+ def from_json(cls, json_str: str) -> Optional[Self]:
50
+ """Create an instance of ZkLighterInfo from a JSON string"""
51
+ return cls.from_dict(json.loads(json_str))
52
+
53
+ def to_dict(self) -> Dict[str, Any]:
54
+ """Return the dictionary representation of the model using alias.
55
+
56
+ This has the following differences from calling pydantic's
57
+ `self.model_dump(by_alias=True)`:
58
+
59
+ * `None` is only added to the output dict for nullable fields that
60
+ were set at model initialization. Other fields with value `None`
61
+ are ignored.
62
+ """
63
+ excluded_fields: Set[str] = set([
64
+ ])
65
+
66
+ _dict = self.model_dump(
67
+ by_alias=True,
68
+ exclude=excluded_fields,
69
+ exclude_none=True,
70
+ )
71
+ return _dict
72
+
73
+ @classmethod
74
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
75
+ """Create an instance of ZkLighterInfo from a dict"""
76
+ if obj is None:
77
+ return None
78
+
79
+ if not isinstance(obj, dict):
80
+ return cls.model_validate(obj)
81
+
82
+ # raise errors for additional fields in the input
83
+ for _key in obj.keys():
84
+ if _key not in cls.__properties:
85
+ raise ValueError("Error due to additional fields (not defined in ZkLighterInfo) in the input: " + _key)
86
+
87
+ _obj = cls.model_validate({
88
+ "contract_address": obj.get("contract_address")
89
+ })
90
+ return _obj
91
+
92
+
lighter/py.typed ADDED
File without changes
lighter/rest.py ADDED
@@ -0,0 +1,215 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+
5
+
6
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
7
+
8
+ The version of the OpenAPI document:
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ import io
16
+ import json
17
+ import re
18
+ import ssl
19
+ from typing import Optional, Union
20
+
21
+ import aiohttp
22
+ import aiohttp_retry
23
+
24
+ from lighter.exceptions import ApiException, ApiValueError
25
+
26
+ RESTResponseType = aiohttp.ClientResponse
27
+
28
+ ALLOW_RETRY_METHODS = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'})
29
+
30
+ class RESTResponse(io.IOBase):
31
+
32
+ def __init__(self, resp) -> None:
33
+ self.response = resp
34
+ self.status = resp.status
35
+ self.reason = resp.reason
36
+ self.data = None
37
+
38
+ async def read(self):
39
+ if self.data is None:
40
+ self.data = await self.response.read()
41
+ return self.data
42
+
43
+ def getheaders(self):
44
+ """Returns a CIMultiDictProxy of the response headers."""
45
+ return self.response.headers
46
+
47
+ def getheader(self, name, default=None):
48
+ """Returns a given response header."""
49
+ return self.response.headers.get(name, default)
50
+
51
+
52
+ class RESTClientObject:
53
+
54
+ def __init__(self, configuration) -> None:
55
+
56
+ # maxsize is number of requests to host that are allowed in parallel
57
+ maxsize = configuration.connection_pool_maxsize
58
+
59
+ ssl_context = ssl.create_default_context(
60
+ cafile=configuration.ssl_ca_cert
61
+ )
62
+ if configuration.cert_file:
63
+ ssl_context.load_cert_chain(
64
+ configuration.cert_file, keyfile=configuration.key_file
65
+ )
66
+
67
+ if not configuration.verify_ssl:
68
+ ssl_context.check_hostname = False
69
+ ssl_context.verify_mode = ssl.CERT_NONE
70
+
71
+ connector = aiohttp.TCPConnector(
72
+ limit=maxsize,
73
+ ssl=ssl_context
74
+ )
75
+
76
+ self.proxy = configuration.proxy
77
+ self.proxy_headers = configuration.proxy_headers
78
+
79
+ # https pool manager
80
+ self.pool_manager = aiohttp.ClientSession(
81
+ connector=connector,
82
+ trust_env=True
83
+ )
84
+
85
+ retries = configuration.retries
86
+ self.retry_client: Optional[aiohttp_retry.RetryClient]
87
+ if retries is not None:
88
+ self.retry_client = aiohttp_retry.RetryClient(
89
+ client_session=self.pool_manager,
90
+ retry_options=aiohttp_retry.ExponentialRetry(
91
+ attempts=retries,
92
+ factor=0.0,
93
+ start_timeout=0.0,
94
+ max_timeout=120.0
95
+ )
96
+ )
97
+ else:
98
+ self.retry_client = None
99
+
100
+ async def close(self):
101
+ await self.pool_manager.close()
102
+ if self.retry_client is not None:
103
+ await self.retry_client.close()
104
+
105
+ async def request(
106
+ self,
107
+ method,
108
+ url,
109
+ headers=None,
110
+ body=None,
111
+ post_params=None,
112
+ _request_timeout=None
113
+ ):
114
+ """Execute request
115
+
116
+ :param method: http request method
117
+ :param url: http request url
118
+ :param headers: http request headers
119
+ :param body: request json body, for `application/json`
120
+ :param post_params: request post parameters,
121
+ `application/x-www-form-urlencoded`
122
+ and `multipart/form-data`
123
+ :param _request_timeout: timeout setting for this request. If one
124
+ number provided, it will be total request
125
+ timeout. It can also be a pair (tuple) of
126
+ (connection, read) timeouts.
127
+ """
128
+ method = method.upper()
129
+ assert method in [
130
+ 'GET',
131
+ 'HEAD',
132
+ 'DELETE',
133
+ 'POST',
134
+ 'PUT',
135
+ 'PATCH',
136
+ 'OPTIONS'
137
+ ]
138
+
139
+ if post_params and body:
140
+ raise ApiValueError(
141
+ "body parameter cannot be used with post_params parameter."
142
+ )
143
+
144
+ post_params = post_params or {}
145
+ headers = headers or {}
146
+ # url already contains the URL query string
147
+ timeout = _request_timeout or 5 * 60
148
+
149
+ if 'Content-Type' not in headers:
150
+ headers['Content-Type'] = 'application/json'
151
+
152
+ args = {
153
+ "method": method,
154
+ "url": url,
155
+ "timeout": timeout,
156
+ "headers": headers
157
+ }
158
+
159
+ if self.proxy:
160
+ args["proxy"] = self.proxy
161
+ if self.proxy_headers:
162
+ args["proxy_headers"] = self.proxy_headers
163
+
164
+ # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
165
+ if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
166
+ if re.search('json', headers['Content-Type'], re.IGNORECASE):
167
+ if body is not None:
168
+ body = json.dumps(body)
169
+ args["data"] = body
170
+ elif headers['Content-Type'] == 'application/x-www-form-urlencoded':
171
+ args["data"] = aiohttp.FormData(post_params)
172
+ elif headers['Content-Type'] == 'multipart/form-data':
173
+ # must del headers['Content-Type'], or the correct
174
+ # Content-Type which generated by aiohttp
175
+ del headers['Content-Type']
176
+ data = aiohttp.FormData()
177
+ for param in post_params:
178
+ k, v = param
179
+ if isinstance(v, tuple) and len(v) == 3:
180
+ data.add_field(
181
+ k,
182
+ value=v[1],
183
+ filename=v[0],
184
+ content_type=v[2]
185
+ )
186
+ else:
187
+ data.add_field(k, v)
188
+ args["data"] = data
189
+
190
+ # Pass a `bytes` or `str` parameter directly in the body to support
191
+ # other content types than Json when `body` argument is provided
192
+ # in serialized form
193
+ elif isinstance(body, str) or isinstance(body, bytes):
194
+ args["data"] = body
195
+ else:
196
+ # Cannot generate the request from given parameters
197
+ msg = """Cannot prepare a request message for provided
198
+ arguments. Please check that your arguments match
199
+ declared content type."""
200
+ raise ApiException(status=0, reason=msg)
201
+
202
+ pool_manager: Union[aiohttp.ClientSession, aiohttp_retry.RetryClient]
203
+ if self.retry_client is not None and method in ALLOW_RETRY_METHODS:
204
+ pool_manager = self.retry_client
205
+ else:
206
+ pool_manager = self.pool_manager
207
+
208
+ r = await pool_manager.request(**args)
209
+
210
+ return RESTResponse(r)
211
+
212
+
213
+
214
+
215
+