-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathclient.py.twig
More file actions
208 lines (171 loc) · 6.85 KB
/
client.py.twig
File metadata and controls
208 lines (171 loc) · 6.85 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
import requests
import os
from .input_file import InputFile
from .exception import {{spec.title | caseUcfirst}}Exception
from typing import Optional
class Client:
def __init__(self):
self._chunk_size = 5*1024*1024
self._self_signed = False
self._endpoint = '{{spec.endpoint}}'
self._global_headers = {
'content-type': '',
'user-agent' : '{{spec.title | caseUcfirst}}{{ language.name | caseUcfirst }}SDK/{{ sdk.version }} (${os.uname().sysname}; ${os.uname().version}; ${os.uname().machine})',
'x-sdk-name': '{{ sdk.name }}',
'x-sdk-platform': '{{ sdk.platform }}',
'x-sdk-language': '{{ language.name | caseLower }}',
'x-sdk-version': '{{ sdk.version }}',
{% for key,header in spec.global.defaultHeaders %}
'{{key}}' : '{{header}}',
{% endfor %}
}
def set_self_signed(self, status: bool = True):
self._self_signed = status
return self
def set_endpoint(self, endpoint: str):
self._endpoint = endpoint
return self
def add_header(self, key: str, value: str):
self._global_headers[key.lower()] = value
return self
{% for header in spec.global.headers %}
def set_{{header.key | caseSnake}}(self, value: str):
{% if header.description %}
"""{{header.description}}"""
{% endif %}
self._global_headers['{{header.name|lower}}'] = value
return self
{% endfor %}
def call(self, method: str, path: str = '', headers: Optional[dict] = None, params: Optional[dict] = None):
if headers is None:
headers = {}
if params is None:
params = {}
data = {}
json = {}
files = {}
stringify = False
headers = {**self._global_headers, **headers}
if method != 'get':
data = params
params = {}
if headers['content-type'].startswith('application/json'):
json = data
data = {}
if headers['content-type'].startswith('multipart/form-data'):
del headers['content-type']
stringify = True
for key in data.copy():
if isinstance(data[key], InputFile):
files[key] = (data[key].filename, data[key].data)
del data[key]
response = None
try:
response = requests.request( # call method dynamically https://stackoverflow.com/a/4246075/2299554
method=method,
url=self._endpoint + path,
params=self.flatten(params, stringify=stringify),
data=self.flatten(data),
json=json,
files=files,
headers=headers,
verify=(not self._self_signed),
)
response.raise_for_status()
content_type = response.headers['Content-Type']
if content_type.startswith('application/json'):
return response.json()
return response._content
except Exception as e:
if response != None:
content_type = response.headers['Content-Type']
if content_type.startswith('application/json'):
raise {{spec.title | caseUcfirst}}Exception(response.json()['message'], response.status_code, response.json().get('type'), response.json())
else:
raise {{spec.title | caseUcfirst}}Exception(response.text, response.status_code)
else:
raise {{spec.title | caseUcfirst}}Exception(e)
def chunked_upload(
self,
path: str,
headers: Optional[dict] = None,
params: Optional[dict] = None,
param_name: str = '',
on_progress = None,
upload_id: str = ''
):
input_file = params[param_name]
if input_file.source_type == 'path':
size = os.stat(input_file.path).st_size
input = open(input_file.path, 'rb')
elif input_file.source_type == 'bytes':
size = len(input_file.data)
input = input_file.data
if size < self._chunk_size:
if input_file.source_type == 'path':
input_file.data = input.read()
params[param_name] = input_file
return self.call(
'post',
path,
headers,
params
)
offset = 0
counter = 0
if upload_id != 'unique()':
try:
result = self.call('get', path + '/' + upload_id, headers)
counter = result['chunksUploaded']
except:
pass
if counter > 0:
offset = counter * self._chunk_size
input.seek(offset)
while offset < size:
if input_file.source_type == 'path':
input_file.data = input.read(self._chunk_size) or input.read(size - offset)
elif input_file.source_type == 'bytes':
if offset + self._chunk_size < size:
end = offset + self._chunk_size
else:
end = size - offset
input_file.data = input[offset:end]
params[param_name] = input_file
headers["content-range"] = f'bytes {offset}-{min((offset + self._chunk_size) - 1, size)}/{size}'
result = self.call(
'post',
path,
headers,
params,
)
offset = offset + self._chunk_size
if "$id" in result:
headers["x-{{ spec.title | caseLower }}-id"] = result["$id"]
if on_progress is not None:
end = min((((counter * self._chunk_size) + self._chunk_size) - 1), size)
on_progress({
"$id": result["$id"],
"progress": min(offset, size)/size * 100,
"sizeUploaded": end+1,
"chunksTotal": result["chunksTotal"],
"chunksUploaded": result["chunksUploaded"],
})
counter = counter + 1
return result
def flatten(self, data: dict, prefix: str = '', stringify: bool = False):
output = {}
i = 0
for key in data:
value = data[key] if isinstance(data, dict) else key
finalKey = prefix + '[' + key +']' if prefix else key
finalKey = prefix + '[' + str(i) +']' if isinstance(data, list) else finalKey
i += 1
if isinstance(value, list) or isinstance(value, dict):
output = {**output, **self.flatten(value, finalKey, stringify)}
else:
if stringify:
output[finalKey] = str(value)
else:
output[finalKey] = value
return output