-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmixins.py
More file actions
241 lines (188 loc) · 7.61 KB
/
Copy pathmixins.py
File metadata and controls
241 lines (188 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#
# This file is part of the CloudBlue Connect Python OpenAPI Client.
#
# Copyright (c) 2025 CloudBlue. All Rights Reserved.
#
import time
from typing import Any, Dict
from httpx import HTTPError
from requests.exceptions import RequestException, Timeout
from connect.client.exceptions import ClientError
class SyncClientMixin:
def get(self, url: str, **kwargs) -> Any:
"""
Make a GET call to the given url.
Args:
url (str): The url to make the call.
"""
return self.execute('get', url, **kwargs)
def create(self, url: str, payload: Dict = None, **kwargs) -> Any:
"""
Make a POST call to the given url with the payload.
Args:
url (str): The url to make the call.
payload (dict): (Optional) The payload to be used.
"""
kwargs = kwargs or {}
if payload:
kwargs['json'] = payload
return self.execute('post', url, **kwargs)
def update(self, url: str, payload: Dict = None, **kwargs) -> Any:
"""
Make a PUT call to the given url with the payload.
Args:
url (str): The url to make the call.
payload (dict): (Optional) The payload to be used.
"""
kwargs = kwargs or {}
if payload:
kwargs['json'] = payload
return self.execute('put', url, **kwargs)
def delete(self, url: str, payload: Dict = None, **kwargs) -> Any:
"""
Make a DELETE call to the given url with the payload.
Args:
url (str): The url to make the call.
payload (dict): (Optional) The payload to be used.
"""
kwargs = kwargs or {}
if payload:
kwargs['json'] = payload
return self.execute('delete', url, **kwargs)
def execute(self, method: str, path: str, **kwargs) -> Any:
if self._use_specs and self._validate_using_specs and not self.specs.exists(method, path):
# TODO more info, specs version, method etc
raise ClientError(f'The path `{path}` does not exist.')
url = f'{self.endpoint}/{path}'
kwargs = self._prepare_call_kwargs(kwargs)
self.response = None
try:
self._execute_http_call(method, url, kwargs)
if self.response.status_code == 204:
return None
if self.response.headers.get('Content-Type', '').startswith('application/json'):
return self.response.json()
else:
return self.response.content
except RequestException as re:
api_error = self._get_api_error_details() or {}
status_code = self.response.status_code if self.response is not None else None
raise ClientError(status_code=status_code, **api_error) from re
def _execute_http_call(self, method, url, kwargs): # noqa: CCR001
retry_count = 0
while True:
if self.logger:
self.logger.log_request(method, url, kwargs)
try:
self.response = self.session.request(method, url, **kwargs)
if self.logger:
self.logger.log_response(self.response)
except RequestException:
if retry_count < self.max_retries:
retry_count += 1
time.sleep(1)
continue
raise
if ( # pragma: no branch
self.response.status_code >= 500 and retry_count < self.max_retries
):
retry_count += 1
time.sleep(1)
continue
break # pragma: no cover
if self.response.status_code >= 400:
self.response.raise_for_status()
class AsyncClientMixin:
async def get(self, url: str, **kwargs) -> Any:
"""
Make a GET call to the given url.
Args:
url (str): The url to make the call.
"""
return await self.execute('get', url, **kwargs)
async def create(self, url: str, payload: Dict = None, **kwargs) -> Any:
"""
Make a POST call to the given url with the payload.
Args:
url (str): The url to make the call.
payload (dict): (Optional) The payload to be used.
"""
kwargs = kwargs or {}
if payload:
kwargs['json'] = payload
return await self.execute('post', url, **kwargs)
async def update(self, url: str, payload: Dict = None, **kwargs) -> Any:
"""
Make a PUT call to the given url with the payload.
Args:
url (str): The url to make the call.
payload (dict): (Optional) The payload to be used.
"""
kwargs = kwargs or {}
if payload:
kwargs['json'] = payload
return await self.execute('put', url, **kwargs)
async def delete(self, url: str, payload: Dict = None, **kwargs) -> Any:
"""
Make a DELETE call to the given url with the payload.
Args:
url (str): The url to make the call.
payload (dict): (Optional) The payload to be used.
"""
kwargs = kwargs or {}
if payload:
kwargs['json'] = payload
return await self.execute('delete', url, **kwargs)
async def execute(self, method: str, path: str, **kwargs) -> Any:
if self._use_specs and self._validate_using_specs and not self.specs.exists(method, path):
# TODO more info, specs version, method etc
raise ClientError(f'The path `{path}` does not exist.')
url = f'{self.endpoint}/{path}'
kwargs = self._prepare_call_kwargs(kwargs)
url, kwargs = self._fix_url_params(url, kwargs)
self.response = None
try:
await self._execute_http_call(method, url, kwargs)
if self.response.status_code == 204:
return None
if self.response.headers.get('Content-Type', '').startswith('application/json'):
return self.response.json()
else:
return self.response.content
except HTTPError as re:
api_error = self._get_api_error_details() or {}
status_code = self.response.status_code if self.response is not None else None
raise ClientError(status_code=status_code, **api_error) from re
async def _execute_http_call(self, method, url, kwargs):
retry_count = 0
while True:
if self.logger:
self.logger.log_request(method, url, kwargs)
try:
self.response = await self.session.request(method, url, **kwargs)
if self.logger:
self.logger.log_response(self.response)
except HTTPError:
if retry_count < self.max_retries:
retry_count += 1
time.sleep(1)
continue
raise
if ( # pragma: no branch
self.response.status_code >= 500 and retry_count < self.max_retries
):
retry_count += 1
time.sleep(1)
continue
break # pragma: no cover
if self.response.status_code >= 400:
self.response.raise_for_status()
def _fix_url_params(self, url, kwargs):
if 'params' in kwargs:
params = kwargs.pop('params')
qs_fragment = '&'.join([f'{k}={v}' for k, v in params.items()])
join = '?' if '?' not in url else '&'
if url.endswith('?'):
join = ''
url = f'{url}{join}{qs_fragment}'
return url, kwargs