-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclient.py
More file actions
51 lines (39 loc) · 1.42 KB
/
client.py
File metadata and controls
51 lines (39 loc) · 1.42 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
import requests
from .exceptions import *
from requests.exceptions import HTTPError
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
class Client:
def __init__(self, configuration):
self.configuration = configuration
def get(self, path, payload = {}):
r = requests.get(self.url(path), params=payload, headers = self.headers(), timeout = self.configuration.timeout, proxies = self.configuration.proxies)
return self.handle_response(r)
def post(self, path, payload):
r = requests.post(self.url(path), json=payload, headers = self.headers(), timeout = self.configuration.timeout, proxies = self.configuration.proxies)
return self.handle_response(r)
def handle_response(self, r):
try:
r.raise_for_status()
return r.json()
except HTTPError as err:
self.handle_http_error(r, err)
except JSONDecodeError:
raise DetectLanguageError("Error decoding response JSON")
def handle_http_error(self, r, err):
try:
json = r.json()
if not 'error' in json:
raise DetectLanguageError(err)
raise DetectLanguageError(json['error']['message'])
except JSONDecodeError:
raise DetectLanguageError(err)
def url(self, path):
return "https://%s/%s/%s" % (self.configuration.host, self.configuration.api_version, path)
def headers(self):
return {
'User-Agent': self.configuration.user_agent,
'Authorization': 'Bearer ' + self.configuration.api_key,
}