2121from datetime import datetime
2222
2323
24- def request_and_check (method , url , status_code = (200 ,), ** kwargs ):
25- """Function to send a GET request to an URL and check the status code.
24+ def request_and_check (method , url , status_code = (200 ,), retries = 0 , ** kwargs ):
25+ """Send a request with the given method to a URL and check the status code.
2626
2727 Parameters:
2828 method (string): Request method (GET, POST, PUT, DELETE, ...)
2929 url (string): URL as string
3030 status_code (tuple): Tuple of acceptable status codes to check
3131 if it is set; default is 200
32+ retries (int): Maximal number of retries in case of read timeouts
33+ default is 0.
3234 **kwargs:
3335 auth (tuple): Tuple of user and password
3436 timeout (tuple): Tuple of connection timeout and read timeout
@@ -38,15 +40,35 @@ def request_and_check(method, url, status_code=(200,), **kwargs):
3840 Returns:
3941 (dict): returns text of the response as dictionary
4042
41- Throws an error if the request does not have the status_code
43+ Throws an error if the request does not have the right status_code or
44+ the response content cannot be paresd as JSON.
4245 """
43- resp = requests .request (method , url , ** kwargs )
44- # Use resp.raise_for_status() ?
45- if resp .status_code == 401 :
46- raise Exception ("Wrong user or password. Please check your inputs." )
47- elif resp .status_code not in status_code :
48- raise Exception (f"Error { resp .status_code } : { resp .text } " )
49- return json .loads (resp .text )
46+ attempt = 0
47+ while attempt <= retries :
48+ attempt += 1
49+ resp = requests .request (method , url , ** kwargs )
50+ try :
51+ if resp .status_code not in status_code :
52+ resp .raise_for_status ()
53+ except requests .exceptions .ReadTimeout as e :
54+ if attempt >= retries :
55+ raise e
56+ continue
57+ except requests .exceptions .RequestException as e :
58+ if resp .status_code == 401 :
59+ raise Exception (
60+ "Wrong user or password. Please check your inputs."
61+ ) from e
62+ raise requests .exceptions .RequestException (
63+ f"Error { resp .status_code } : { resp .text } " , e
64+ ) from None
65+ try :
66+ return json .loads (resp .text )
67+ except json .JSONDecodeError :
68+ raise RuntimeError (
69+ "Invalid value returned. Cannot parse JSON from response:" ,
70+ resp .text ,
71+ ) from None
5072
5173
5274def set_job_names (name , default_name = "unknown_job" ):
0 commit comments