Skip to content

Commit de912b7

Browse files
COmanage API Request library changes for PR 2
1 parent 820d978 commit de912b7

2 files changed

Lines changed: 22 additions & 25 deletions

File tree

comanage_utils.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import re
55
import json
66
import time
7-
import exceptions
87
import urllib.error
98
import urllib.request
109
from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, SAFE_SYNC
@@ -29,14 +28,24 @@
2928

3029
# Value for the base of the exponential backoff
3130
TIMEOUT_BASE = 5
32-
MAX_RETRIES = 5
31+
MAX_ATTEMPTS = 5
3332

3433

3534
GET = "GET"
3635
PUT = "PUT"
3736
POST = "POST"
3837
DELETE = "DELETE"
3938

39+
#Exceptions
40+
class Error(Exception):
41+
"""Base exception class for all exceptions defined"""
42+
pass
43+
44+
45+
class URLRequestError(Error):
46+
"""Class for exceptions due to not being able to fulfill a URLRequest"""
47+
pass
48+
4049

4150
def getpw(user, passfd, passfile):
4251
if ":" in user:
@@ -81,29 +90,28 @@ def call_api2(method, target, endpoint, authstr, **kw):
8190

8291
def call_api3(method, target, data, endpoint, authstr, **kw):
8392
req = mkrequest(method, target, data, endpoint, authstr, **kw)
84-
retries = 0
93+
req_attempts = 0
8594
current_timeout = TIMEOUT_BASE
8695
total_timeout = 0
8796
payload = None
88-
while retries <= MAX_RETRIES:
97+
while req_attempts < MAX_ATTEMPTS:
8998
try:
9099
resp = urllib.request.urlopen(req, timeout=current_timeout)
91-
payload = resp.read()
92-
break
93-
# exception catching, mainly for request timeouts and "Service Temporarily Unavailable" (Rate limiting).
94-
except urllib.error.HTTPError as exception:
95-
if retries >= MAX_RETRIES:
96-
raise exceptions.URLRequestError(
100+
# exception catching, mainly for request timeouts, "Service Temporarily Unavailable" (Rate limiting), and DNS failures.
101+
except urllib.error.URLError as exception:
102+
req_attempts += 1
103+
if req_attempts >= MAX_ATTEMPTS:
104+
raise URLRequestError(
97105
"Exception raised after maximum number of retries reached after total backoff of " +
98-
f"{total_timeout} seconds. Retries: {retries}. "
106+
f"{total_timeout} seconds. Retries: {req_attempts}. "
99107
+ f"Exception reason: {exception}.\n Request: {req.full_url}"
100108
)
101-
102-
print("waiting for seconds: " + str(current_timeout))
103109
time.sleep(current_timeout)
104110
total_timeout += current_timeout
105111
current_timeout *= TIMEOUT_BASE
106-
retries += 1
112+
else:
113+
payload = resp.read()
114+
break
107115

108116
return json.loads(payload) if payload else None
109117

exceptions.py

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)