-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathhttp_client.py
More file actions
43 lines (34 loc) · 1.55 KB
/
http_client.py
File metadata and controls
43 lines (34 loc) · 1.55 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
import json
import socket
import certifi
from urllib3 import PoolManager
from urllib3.exceptions import HTTPError
from cloudinary.exceptions import GeneralError
class HttpClient:
DEFAULT_HTTP_TIMEOUT = 60
def __init__(self, **options):
# Lazy initialization of the client, to improve performance when HttpClient is initialized but not used
self._http_client_instance = None
self.timeout = options.get("timeout", self.DEFAULT_HTTP_TIMEOUT)
@property
def _http_client(self):
if self._http_client_instance is None:
self._http_client_instance = PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
return self._http_client_instance
def get_json(self, url):
try:
response = self._http_client.request(method="GET", url=url, timeout=self.timeout)
body = response.data
except HTTPError as e:
raise GeneralError("Unexpected error %s" % str(e))
except socket.error as e:
raise GeneralError("Socket Error: %s" % str(e))
if response.status != 200:
raise GeneralError("Server returned unexpected status code - {} - {}".format(response.status,
response.data))
try:
result = json.loads(body.decode('utf-8'))
except Exception as e:
# Error is parsing json
raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.status, body, e))
return result