-
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.71 KB
/
client.py
File metadata and controls
65 lines (50 loc) · 1.71 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
import simplejson
from io import BytesIO
from .exceptions import *
class Client:
def get(self, path, params = {}, timeout = None):
timeout = timeout or convertapi.timeout
r = requests.get(self.url(path), params = params, headers = self.headers(), timeout = timeout)
return self.handle_response(r)
def post(self, path, payload, timeout = None):
timeout = timeout or convertapi.timeout
r = requests.post(self.url(path), data = payload, headers = self.headers(), timeout = timeout)
return self.handle_response(r)
def upload(self, io, filename):
url = convertapi.base_uri + 'upload'
encoded_filename = requests.utils.quote(filename)
headers = self.headers()
headers.update({
'Content-Disposition': "attachment; filename*=UTF-8''" + encoded_filename,
})
r = requests.post(url, data = io, headers = headers, timeout = convertapi.upload_timeout)
return self.handle_response(r)
def download(self, url, path):
r = requests.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 = requests.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
if r.content == b'':
raise AsyncConversionInProgress
return r.json()
def url(self, path):
return "%s%s?Secret=%s" % (convertapi.base_uri, path, convertapi.api_secret)
def headers(self):
return {
'User-Agent': convertapi.user_agent,
}