rapidata 2.17.1__py3-none-any.whl → 2.19.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.

Potentially problematic release.


This version of rapidata might be problematic. Click here for more details.

Files changed (38) hide show
  1. rapidata/__init__.py +2 -0
  2. rapidata/api_client/__init__.py +7 -5
  3. rapidata/api_client/api/order_api.py +3 -6
  4. rapidata/api_client/api/pipeline_api.py +665 -98
  5. rapidata/api_client/api/validation_set_api.py +6 -6
  6. rapidata/api_client/models/__init__.py +7 -5
  7. rapidata/api_client/models/add_user_response_result.py +3 -3
  8. rapidata/api_client/models/campaign_query_result.py +2 -2
  9. rapidata/api_client/models/campaign_status.py +2 -1
  10. rapidata/api_client/models/create_order_model_user_filters_inner.py +39 -9
  11. rapidata/api_client/models/get_simple_workflow_results_result.py +3 -3
  12. rapidata/api_client/models/get_validation_rapids_result.py +143 -0
  13. rapidata/api_client/models/get_validation_rapids_result_asset.py +174 -0
  14. rapidata/api_client/models/get_validation_rapids_result_paged_result.py +105 -0
  15. rapidata/api_client/models/get_validation_rapids_result_payload.py +252 -0
  16. rapidata/api_client/models/get_validation_rapids_result_truth.py +258 -0
  17. rapidata/api_client/models/not_user_filter_model.py +102 -0
  18. rapidata/api_client/models/or_user_filter_model.py +106 -0
  19. rapidata/api_client/models/query_validation_rapids_result.py +9 -9
  20. rapidata/api_client/rest.py +143 -169
  21. rapidata/api_client_README.md +9 -5
  22. rapidata/rapidata_client/__init__.py +2 -0
  23. rapidata/rapidata_client/filter/__init__.py +2 -0
  24. rapidata/rapidata_client/filter/not_filter.py +30 -0
  25. rapidata/rapidata_client/filter/or_filter.py +30 -0
  26. rapidata/rapidata_client/filter/rapidata_filters.py +6 -3
  27. rapidata/rapidata_client/order/rapidata_order.py +2 -2
  28. rapidata/rapidata_client/rapidata_client.py +27 -16
  29. rapidata/rapidata_client/selection/__init__.py +2 -0
  30. rapidata/rapidata_client/selection/static_selection.py +22 -0
  31. rapidata/rapidata_client/validation/validation_set_manager.py +1 -1
  32. rapidata/service/credential_manager.py +2 -2
  33. rapidata/service/openapi_service.py +56 -28
  34. {rapidata-2.17.1.dist-info → rapidata-2.19.0.dist-info}/METADATA +2 -1
  35. {rapidata-2.17.1.dist-info → rapidata-2.19.0.dist-info}/RECORD +37 -28
  36. rapidata/service/token_manager.py +0 -176
  37. {rapidata-2.17.1.dist-info → rapidata-2.19.0.dist-info}/LICENSE +0 -0
  38. {rapidata-2.17.1.dist-info → rapidata-2.19.0.dist-info}/WHEEL +0 -0
@@ -0,0 +1,102 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Rapidata.Dataset
5
+
6
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
7
+
8
+ The version of the OpenAPI document: v1
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, Field, 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 NotUserFilterModel(BaseModel):
26
+ """
27
+ NotUserFilterModel
28
+ """ # noqa: E501
29
+ t: StrictStr = Field(description="Discriminator value for NotFilter", alias="_t")
30
+ filter: CreateOrderModelUserFiltersInner
31
+ __properties: ClassVar[List[str]] = ["_t", "filter"]
32
+
33
+ @field_validator('t')
34
+ def t_validate_enum(cls, value):
35
+ """Validates the enum"""
36
+ if value not in set(['NotFilter']):
37
+ raise ValueError("must be one of enum values ('NotFilter')")
38
+ return value
39
+
40
+ model_config = ConfigDict(
41
+ populate_by_name=True,
42
+ validate_assignment=True,
43
+ protected_namespaces=(),
44
+ )
45
+
46
+
47
+ def to_str(self) -> str:
48
+ """Returns the string representation of the model using alias"""
49
+ return pprint.pformat(self.model_dump(by_alias=True))
50
+
51
+ def to_json(self) -> str:
52
+ """Returns the JSON representation of the model using alias"""
53
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
54
+ return json.dumps(self.to_dict())
55
+
56
+ @classmethod
57
+ def from_json(cls, json_str: str) -> Optional[Self]:
58
+ """Create an instance of NotUserFilterModel from a JSON string"""
59
+ return cls.from_dict(json.loads(json_str))
60
+
61
+ def to_dict(self) -> Dict[str, Any]:
62
+ """Return the dictionary representation of the model using alias.
63
+
64
+ This has the following differences from calling pydantic's
65
+ `self.model_dump(by_alias=True)`:
66
+
67
+ * `None` is only added to the output dict for nullable fields that
68
+ were set at model initialization. Other fields with value `None`
69
+ are ignored.
70
+ """
71
+ excluded_fields: Set[str] = set([
72
+ ])
73
+
74
+ _dict = self.model_dump(
75
+ by_alias=True,
76
+ exclude=excluded_fields,
77
+ exclude_none=True,
78
+ )
79
+ # override the default output from pydantic by calling `to_dict()` of filter
80
+ if self.filter:
81
+ _dict['filter'] = self.filter.to_dict()
82
+ return _dict
83
+
84
+ @classmethod
85
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
86
+ """Create an instance of NotUserFilterModel from a dict"""
87
+ if obj is None:
88
+ return None
89
+
90
+ if not isinstance(obj, dict):
91
+ return cls.model_validate(obj)
92
+
93
+ _obj = cls.model_validate({
94
+ "_t": obj.get("_t") if obj.get("_t") is not None else 'NotFilter',
95
+ "filter": CreateOrderModelUserFiltersInner.from_dict(obj["filter"]) if obj.get("filter") is not None else None
96
+ })
97
+ return _obj
98
+
99
+ from rapidata.api_client.models.create_order_model_user_filters_inner import CreateOrderModelUserFiltersInner
100
+ # TODO: Rewrite to not use raise_errors
101
+ NotUserFilterModel.model_rebuild(raise_errors=False)
102
+
@@ -0,0 +1,106 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Rapidata.Dataset
5
+
6
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
7
+
8
+ The version of the OpenAPI document: v1
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, Field, 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 OrUserFilterModel(BaseModel):
26
+ """
27
+ OrUserFilterModel
28
+ """ # noqa: E501
29
+ t: StrictStr = Field(description="Discriminator value for OrFilter", alias="_t")
30
+ filters: List[CreateOrderModelUserFiltersInner]
31
+ __properties: ClassVar[List[str]] = ["_t", "filters"]
32
+
33
+ @field_validator('t')
34
+ def t_validate_enum(cls, value):
35
+ """Validates the enum"""
36
+ if value not in set(['OrFilter']):
37
+ raise ValueError("must be one of enum values ('OrFilter')")
38
+ return value
39
+
40
+ model_config = ConfigDict(
41
+ populate_by_name=True,
42
+ validate_assignment=True,
43
+ protected_namespaces=(),
44
+ )
45
+
46
+
47
+ def to_str(self) -> str:
48
+ """Returns the string representation of the model using alias"""
49
+ return pprint.pformat(self.model_dump(by_alias=True))
50
+
51
+ def to_json(self) -> str:
52
+ """Returns the JSON representation of the model using alias"""
53
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
54
+ return json.dumps(self.to_dict())
55
+
56
+ @classmethod
57
+ def from_json(cls, json_str: str) -> Optional[Self]:
58
+ """Create an instance of OrUserFilterModel from a JSON string"""
59
+ return cls.from_dict(json.loads(json_str))
60
+
61
+ def to_dict(self) -> Dict[str, Any]:
62
+ """Return the dictionary representation of the model using alias.
63
+
64
+ This has the following differences from calling pydantic's
65
+ `self.model_dump(by_alias=True)`:
66
+
67
+ * `None` is only added to the output dict for nullable fields that
68
+ were set at model initialization. Other fields with value `None`
69
+ are ignored.
70
+ """
71
+ excluded_fields: Set[str] = set([
72
+ ])
73
+
74
+ _dict = self.model_dump(
75
+ by_alias=True,
76
+ exclude=excluded_fields,
77
+ exclude_none=True,
78
+ )
79
+ # override the default output from pydantic by calling `to_dict()` of each item in filters (list)
80
+ _items = []
81
+ if self.filters:
82
+ for _item_filters in self.filters:
83
+ if _item_filters:
84
+ _items.append(_item_filters.to_dict())
85
+ _dict['filters'] = _items
86
+ return _dict
87
+
88
+ @classmethod
89
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
90
+ """Create an instance of OrUserFilterModel 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
+ _obj = cls.model_validate({
98
+ "_t": obj.get("_t") if obj.get("_t") is not None else 'OrFilter',
99
+ "filters": [CreateOrderModelUserFiltersInner.from_dict(_item) for _item in obj["filters"]] if obj.get("filters") is not None else None
100
+ })
101
+ return _obj
102
+
103
+ from rapidata.api_client.models.create_order_model_user_filters_inner import CreateOrderModelUserFiltersInner
104
+ # TODO: Rewrite to not use raise_errors
105
+ OrUserFilterModel.model_rebuild(raise_errors=False)
106
+
@@ -19,10 +19,10 @@ import json
19
19
 
20
20
  from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
21
21
  from typing import Any, ClassVar, Dict, List, Optional
22
- from rapidata.api_client.models.add_user_response_result_validation_truth import AddUserResponseResultValidationTruth
23
22
  from rapidata.api_client.models.file_asset_model_metadata_value import FileAssetModelMetadataValue
24
- from rapidata.api_client.models.query_validation_rapids_result_asset import QueryValidationRapidsResultAsset
25
- from rapidata.api_client.models.query_validation_rapids_result_payload import QueryValidationRapidsResultPayload
23
+ from rapidata.api_client.models.get_validation_rapids_result_asset import GetValidationRapidsResultAsset
24
+ from rapidata.api_client.models.get_validation_rapids_result_payload import GetValidationRapidsResultPayload
25
+ from rapidata.api_client.models.get_validation_rapids_result_truth import GetValidationRapidsResultTruth
26
26
  from typing import Optional, Set
27
27
  from typing_extensions import Self
28
28
 
@@ -32,9 +32,9 @@ class QueryValidationRapidsResult(BaseModel):
32
32
  """ # noqa: E501
33
33
  id: StrictStr
34
34
  type: StrictStr
35
- asset: Optional[QueryValidationRapidsResultAsset] = None
36
- truth: Optional[AddUserResponseResultValidationTruth] = None
37
- payload: QueryValidationRapidsResultPayload
35
+ asset: Optional[GetValidationRapidsResultAsset] = None
36
+ truth: Optional[GetValidationRapidsResultTruth] = None
37
+ payload: GetValidationRapidsResultPayload
38
38
  metadata: Dict[str, FileAssetModelMetadataValue]
39
39
  correct_validation_count: StrictInt = Field(alias="correctValidationCount")
40
40
  invalid_validation_count: StrictInt = Field(alias="invalidValidationCount")
@@ -125,9 +125,9 @@ class QueryValidationRapidsResult(BaseModel):
125
125
  _obj = cls.model_validate({
126
126
  "id": obj.get("id"),
127
127
  "type": obj.get("type"),
128
- "asset": QueryValidationRapidsResultAsset.from_dict(obj["asset"]) if obj.get("asset") is not None else None,
129
- "truth": AddUserResponseResultValidationTruth.from_dict(obj["truth"]) if obj.get("truth") is not None else None,
130
- "payload": QueryValidationRapidsResultPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None,
128
+ "asset": GetValidationRapidsResultAsset.from_dict(obj["asset"]) if obj.get("asset") is not None else None,
129
+ "truth": GetValidationRapidsResultTruth.from_dict(obj["truth"]) if obj.get("truth") is not None else None,
130
+ "payload": GetValidationRapidsResultPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None,
131
131
  "metadata": dict(
132
132
  (_k, FileAssetModelMetadataValue.from_dict(_v))
133
133
  for _k, _v in obj["metadata"].items()
@@ -11,114 +11,86 @@
11
11
  Do not edit the class manually.
12
12
  """ # noqa: E501
13
13
 
14
-
15
14
  import io
16
15
  import json
17
16
  import re
18
- import ssl
17
+ from typing import Dict, Optional
19
18
 
20
- import urllib3
19
+ import requests
20
+ from authlib.integrations.requests_client import OAuth2Session
21
+ from requests.adapters import HTTPAdapter
22
+ from urllib3 import Retry
21
23
 
22
24
  from rapidata.api_client.exceptions import ApiException, ApiValueError
23
25
 
24
- SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"}
25
- RESTResponseType = urllib3.HTTPResponse
26
-
27
-
28
- def is_socks_proxy_url(url):
29
- if url is None:
30
- return False
31
- split_section = url.split("://")
32
- if len(split_section) < 2:
33
- return False
34
- else:
35
- return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES
36
-
37
26
 
38
27
  class RESTResponse(io.IOBase):
39
28
 
40
- def __init__(self, resp) -> None:
29
+ def __init__(self, resp: requests.Response) -> None:
41
30
  self.response = resp
42
- self.status = resp.status
31
+ self.status = resp.status_code
43
32
  self.reason = resp.reason
44
33
  self.data = None
45
34
 
46
35
  def read(self):
47
36
  if self.data is None:
48
- self.data = self.response.data
37
+ self.data = self.response.content
49
38
  return self.data
50
39
 
51
- def getheaders(self):
40
+ def getheaders(self) -> Dict[str, str]:
52
41
  """Returns a dictionary of the response headers."""
53
- return self.response.headers
42
+ return dict(self.response.headers)
54
43
 
55
- def getheader(self, name, default=None):
44
+ def getheader(self, name, default=None) -> Optional[str]:
56
45
  """Returns a given response header."""
57
46
  return self.response.headers.get(name, default)
58
47
 
59
48
 
60
- class RESTClientObject:
61
-
62
- def __init__(self, configuration) -> None:
63
- # urllib3.PoolManager will pass all kw parameters to connectionpool
64
- # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501
65
- # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501
66
- # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501
67
-
68
- # cert_reqs
69
- if configuration.verify_ssl:
70
- cert_reqs = ssl.CERT_REQUIRED
71
- else:
72
- cert_reqs = ssl.CERT_NONE
73
-
74
- pool_args = {
75
- "cert_reqs": cert_reqs,
76
- "ca_certs": configuration.ssl_ca_cert,
77
- "cert_file": configuration.cert_file,
78
- "key_file": configuration.key_file,
79
- }
80
- if configuration.assert_hostname is not None:
81
- pool_args['assert_hostname'] = (
82
- configuration.assert_hostname
83
- )
49
+ RESTResponseType = RESTResponse
84
50
 
85
- if configuration.retries is not None:
86
- pool_args['retries'] = configuration.retries
87
51
 
88
- if configuration.tls_server_name:
89
- pool_args['server_hostname'] = configuration.tls_server_name
90
-
91
-
92
- if configuration.socket_options is not None:
93
- pool_args['socket_options'] = configuration.socket_options
52
+ class RESTClientObject:
94
53
 
95
- if configuration.connection_pool_maxsize is not None:
96
- pool_args['maxsize'] = configuration.connection_pool_maxsize
54
+ def __init__(self, configuration) -> None:
55
+ self.configuration = configuration
97
56
 
98
- # https pool manager
99
- self.pool_manager: urllib3.PoolManager
57
+ self.session: Optional[OAuth2Session] = None
100
58
 
101
- if configuration.proxy:
102
- if is_socks_proxy_url(configuration.proxy):
103
- from urllib3.contrib.socks import SOCKSProxyManager
104
- pool_args["proxy_url"] = configuration.proxy
105
- pool_args["headers"] = configuration.proxy_headers
106
- self.pool_manager = SOCKSProxyManager(**pool_args)
107
- else:
108
- pool_args["proxy_url"] = configuration.proxy
109
- pool_args["proxy_headers"] = configuration.proxy_headers
110
- self.pool_manager = urllib3.ProxyManager(**pool_args)
111
- else:
112
- self.pool_manager = urllib3.PoolManager(**pool_args)
59
+ def setup_oauth_client_credentials(
60
+ self, client_id: str, client_secret: str, token_endpoint: str, scope: str
61
+ ):
62
+ self.session = OAuth2Session(
63
+ client_id=client_id,
64
+ client_secret=client_secret,
65
+ token_endpoint=token_endpoint,
66
+ scope=scope,
67
+ )
68
+ self._configure_session_defaults()
69
+ self.session.fetch_token()
70
+
71
+ def setup_oauth_with_token(self,
72
+ client_id: str | None,
73
+ client_secret: str | None,
74
+ token: dict,
75
+ token_endpoint: str,
76
+ leeway: int = 60):
77
+ self.session = OAuth2Session(
78
+ token=token,
79
+ token_endpoint=token_endpoint,
80
+ client_id=client_id,
81
+ client_secret=client_secret,
82
+ leeway=leeway,
83
+ )
84
+ self._configure_session_defaults()
113
85
 
114
86
  def request(
115
- self,
116
- method,
117
- url,
118
- headers=None,
119
- body=None,
120
- post_params=None,
121
- _request_timeout=None
87
+ self,
88
+ method,
89
+ url,
90
+ headers=None,
91
+ body=None,
92
+ post_params=None,
93
+ _request_timeout=None,
122
94
  ):
123
95
  """Perform requests.
124
96
 
@@ -135,15 +107,7 @@ class RESTClientObject:
135
107
  (connection, read) timeouts.
136
108
  """
137
109
  method = method.upper()
138
- assert method in [
139
- 'GET',
140
- 'HEAD',
141
- 'DELETE',
142
- 'POST',
143
- 'PUT',
144
- 'PATCH',
145
- 'OPTIONS'
146
- ]
110
+ assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"]
147
111
 
148
112
  if post_params and body:
149
113
  raise ApiValueError(
@@ -153,105 +117,115 @@ class RESTClientObject:
153
117
  post_params = post_params or {}
154
118
  headers = headers or {}
155
119
 
120
+ if not self.session:
121
+ raise ApiValueError(
122
+ "OAuth2 session is not initialized. Please initialize it before making requests."
123
+ )
124
+
125
+ session = self.session
126
+
156
127
  timeout = None
157
128
  if _request_timeout:
158
129
  if isinstance(_request_timeout, (int, float)):
159
- timeout = urllib3.Timeout(total=_request_timeout)
160
- elif (
161
- isinstance(_request_timeout, tuple)
162
- and len(_request_timeout) == 2
163
- ):
164
- timeout = urllib3.Timeout(
165
- connect=_request_timeout[0],
166
- read=_request_timeout[1]
167
- )
130
+ timeout = _request_timeout
131
+ elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2:
132
+ timeout = _request_timeout
168
133
 
169
134
  try:
170
- # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
171
- if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
172
-
173
- # no content type provided or payload is json
174
- content_type = headers.get('Content-Type')
175
- if (
176
- not content_type
177
- or re.search('json', content_type, re.IGNORECASE)
178
- ):
135
+ if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]:
136
+ content_type = headers.get("Content-Type")
137
+
138
+ if not content_type or re.search("json", content_type, re.IGNORECASE):
179
139
  request_body = None
180
140
  if body is not None:
181
141
  request_body = json.dumps(body)
182
- r = self.pool_manager.request(
183
- method,
184
- url,
185
- body=request_body,
186
- timeout=timeout,
187
- headers=headers,
188
- preload_content=False
189
- )
142
+ r = session.request(method, url, data=request_body, timeout=timeout, headers=headers)
143
+
190
144
  elif content_type == 'application/x-www-form-urlencoded':
191
- r = self.pool_manager.request(
192
- method,
193
- url,
194
- fields=post_params,
195
- encode_multipart=False,
196
- timeout=timeout,
197
- headers=headers,
198
- preload_content=False
199
- )
145
+ r = session.request(method, url, data=post_params, timeout=timeout, headers=headers)
146
+
200
147
  elif content_type == 'multipart/form-data':
201
- # must del headers['Content-Type'], or the correct
202
- # Content-Type which generated by urllib3 will be
203
- # overwritten.
204
148
  del headers['Content-Type']
205
- # Ensures that dict objects are serialized
206
- post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params]
207
- r = self.pool_manager.request(
208
- method,
209
- url,
210
- fields=post_params,
211
- encode_multipart=True,
212
- timeout=timeout,
213
- headers=headers,
214
- preload_content=False
215
- )
216
- # Pass a `string` parameter directly in the body to support
217
- # other content types than JSON when `body` argument is
218
- # provided in serialized form.
149
+ files = []
150
+ data = {}
151
+
152
+ for key, value in post_params:
153
+ if isinstance(value, tuple) and len(value) >= 2:
154
+ # This is a file tuple (filename, file_data, [content_type])
155
+ filename, file_data = value[0], value[1]
156
+ content_type = value[2] if len(value) > 2 else None
157
+ files.append((key, (filename, file_data, content_type)))
158
+ elif isinstance(value, dict):
159
+ # JSON-serialize dictionary values
160
+ if key in data:
161
+ # If we already have this key, handle as needed
162
+ # (convert to list or append to existing list)
163
+ if not isinstance(data[key], list):
164
+ data[key] = [data[key]]
165
+ data[key].append(json.dumps(value))
166
+ else:
167
+ data[key] = json.dumps(value)
168
+ else:
169
+ # Regular form data
170
+ if key in data:
171
+ if not isinstance(data[key], list):
172
+ data[key] = [data[key]]
173
+ data[key].append(value)
174
+ else:
175
+ data[key] = value
176
+ r = session.request(method, url, files=files, data=data, timeout=timeout, headers=headers)
177
+
219
178
  elif isinstance(body, str) or isinstance(body, bytes):
220
- r = self.pool_manager.request(
221
- method,
222
- url,
223
- body=body,
224
- timeout=timeout,
225
- headers=headers,
226
- preload_content=False
227
- )
179
+ r = session.request(method, url, data=body, timeout=timeout, headers=headers)
180
+
228
181
  elif headers['Content-Type'].startswith('text/') and isinstance(body, bool):
229
- request_body = "true" if body else "false"
230
- r = self.pool_manager.request(
231
- method,
232
- url,
233
- body=request_body,
234
- preload_content=False,
235
- timeout=timeout,
236
- headers=headers)
182
+ request_body = 'true' if body else 'false'
183
+ r = session.request(method, url, data=request_body, timeout=timeout, headers=headers)
184
+
237
185
  else:
238
- # Cannot generate the request from given parameters
239
- msg = """Cannot prepare a request message for provided
240
- arguments. Please check that your arguments match
241
- declared content type."""
186
+ msg = '''Cannot prepare a request message for provided arguments.
187
+ Please check that your arguments match declared content type.'''
242
188
  raise ApiException(status=0, reason=msg)
243
- # For `GET`, `HEAD`
189
+
244
190
  else:
245
- r = self.pool_manager.request(
246
- method,
247
- url,
248
- fields={},
249
- timeout=timeout,
250
- headers=headers,
251
- preload_content=False
252
- )
253
- except urllib3.exceptions.SSLError as e:
254
- msg = "\n".join([type(e).__name__, str(e)])
191
+ r = session.request(method, url, params={}, timeout=timeout, headers=headers)
192
+
193
+ except requests.exceptions.SSLError as e:
194
+ msg = '\n'.join([type(e).__name__, str(e)])
255
195
  raise ApiException(status=0, reason=msg)
256
196
 
257
197
  return RESTResponse(r)
198
+
199
+ def _configure_session_defaults(self):
200
+ self.session.verify = (
201
+ self.configuration.ssl_ca_cert
202
+ if self.configuration.ssl_ca_cert
203
+ else self.configuration.verify_ssl
204
+ )
205
+
206
+ if self.configuration.cert_file and self.configuration.key_file:
207
+ self.session.cert = (
208
+ self.configuration.cert_file,
209
+ self.configuration.key_file,
210
+ )
211
+
212
+ if self.configuration.retries is not None:
213
+ retry = Retry(
214
+ total=self.configuration.retries,
215
+ backoff_factor=0.3,
216
+ status_forcelist=[429, 500, 502, 503, 504],
217
+ )
218
+ adapter = HTTPAdapter(max_retries=retry)
219
+ self.session.mount("https://", adapter)
220
+ # noinspection HttpUrlsUsage
221
+ self.session.mount("http://", adapter)
222
+
223
+ if self.configuration.proxy:
224
+ self.session.proxies = {
225
+ "http": self.configuration.proxy,
226
+ "https": self.configuration.proxy,
227
+ }
228
+
229
+ if self.configuration.proxy_headers:
230
+ for key, value in self.configuration.proxy_headers.items():
231
+ self.session.headers[key] = value