Skip to content

Commit d1dc57c

Browse files
author
Christian Geie
committed
return a response object in any cases
to avoid returning "none" which would lead to an AttributeError in the caller code. add exception handling for SSLError and RetryError add debug log message for dummy response
1 parent 12eaa68 commit d1dc57c

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

src/helpers.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from requests.adapters import HTTPAdapter
1212
from requests.auth import HTTPBasicAuth
1313
from requests.packages.urllib3.util.retry import Retry
14+
from types import SimpleNamespace
1415

1516
from logger import get_logger
1617
import argparse
@@ -166,18 +167,27 @@ def request(url, method, enable_5xx=False, payload=None):
166167
logger.warning(f"No url provided. Doing nothing.")
167168
return
168169

169-
# If method is not provided use GET as default
170-
if method == "GET" or not method:
171-
res = r.get("%s" % url, auth=auth, timeout=REQ_TIMEOUT, verify=REQ_TLS_VERIFY)
172-
logger.info(f"Request sent to {url}." f"Response: {res.status_code} {res.reason} {res.text}")
173-
elif method == "POST":
174-
res = r.post("%s" % url, auth=auth, json=payload, timeout=REQ_TIMEOUT, verify=REQ_TLS_VERIFY)
175-
logger.info(f"{payload} sent to {url}." f"Response: {res.status_code} {res.reason} {res.text}")
176-
else:
177-
logger.warning(f"Invalid REQ_METHOD: '{method}', please use 'GET' or 'POST'. Doing nothing.")
178-
return
179-
return res
180-
170+
try:
171+
# If method is not provided use GET as default
172+
if method == "GET" or not method:
173+
res = r.get("%s" % url, auth=auth, timeout=REQ_TIMEOUT, verify=REQ_TLS_VERIFY)
174+
logger.info(f"Request sent to {url}. Response: {res.status_code} {res.reason} {res.text}")
175+
elif method == "POST":
176+
res = r.post("%s" % url, auth=auth, json=payload, timeout=REQ_TIMEOUT, verify=REQ_TLS_VERIFY)
177+
logger.info(f"{payload} sent to {url}. Response: {res.status_code} {res.reason} {res.text}")
178+
else:
179+
logger.warning(f"Invalid REQ_METHOD: '{method}', please use 'GET' or 'POST'. Doing nothing.")
180+
return
181+
return res
182+
except requests.exceptions.SSLError as e:
183+
logger.error(f"SSL certificate verification failed for URL {url}: {e}")
184+
except requests.exceptions.RetryError as e:
185+
logger.error(f"Max retries exceeded for URL {url}: {e}")
186+
except Exception as e:
187+
logger.error(f"Unexpected error during request to {url}: {e}")
188+
# Return a dummy-object with empty attributes to avoid AttributeError if no response is returned (e.g. MaxRetryError)
189+
logger.debug(f"Returning dummy response for URL {url}")
190+
return SimpleNamespace(text="", content=b"")
181191

182192
def timestamp():
183193
"""Get a timestamp of the current time for logging."""

0 commit comments

Comments
 (0)