-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathclient.py
More file actions
65 lines (50 loc) · 1.74 KB
/
client.py
File metadata and controls
65 lines (50 loc) · 1.74 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
import requests
import convertapi
from io import BytesIO
from .exceptions import *
class Client:
def get(self, path, params = {}, timeout = None):
url = self.__url(path)
timeout = timeout or convertapi.timeout
r = self.__session().get(url, params = params, timeout = timeout)
return self.__handle_response(r)
def post(self, path, payload, timeout = None):
url = self.__url(path)
timeout = timeout or convertapi.timeout
r = self.__session().post(url, data = payload, timeout = timeout)
return self.__handle_response(r)
def upload(self, io, filename):
url = convertapi.base_uri + 'upload'
encoded_filename = requests.utils.quote(filename)
headers = {
'Content-Disposition': "attachment; filename*=UTF-8''" + encoded_filename,
}
r = self.__session().post(url, data = io, headers = headers, timeout = convertapi.upload_timeout)
return self.__handle_response(r)
def download(self, url, path):
r = self.__session().get(url, stream = True, timeout = convertapi.download_timeout)
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size = 1024):
if chunk:
f.write(chunk)
return path
def download_io(self, url):
response = self.__session().get(url, timeout = convertapi.download_timeout)
return BytesIO(response.content)
def __handle_response(self, r):
try:
r.raise_for_status()
except requests.RequestException as e:
try:
raise ApiError(r.json())
except ValueError:
raise e
return r.json()
def __url(self, path):
return convertapi.base_uri + path
def __session(self):
s = requests.Session()
s.headers.update({ 'User-Agent': convertapi.user_agent })
s.headers.update({ 'Authorization': 'Bearer ' + convertapi.api_credentials })
s.verify = convertapi.verify_ssl
return s