Skip to content

Commit 667b54d

Browse files
committed
user-test-activity download_value +retries
Do number of retries on response.status_code 429
1 parent e0ecfc3 commit 667b54d

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

user-test-activity3.py

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import argparse
66
import HTTPAuthOptions
7+
import time
78

89
# OData service base URL
910
#BASE_URL = "https://dhr1.cesnet.cz/odata/v2"
@@ -48,22 +49,39 @@ def get_products(auth, queries):
4849

4950
return products_by_query
5051

51-
def download_value(entity, entity_id, auth, entity_type, node_ids=None):
52-
"""Download entity's $value (binary content) to tmp."""
52+
def download_value(entity, entity_id, auth, entity_type, node_ids=None, retries=3):
53+
"""Download entity's $value (binary content) to tmp. Retries on HTTP 429."""
5354
if entity_type == 'Nodes':
5455
url = f"{BASE_URL}/Products({entity_id})/{nodes_to_url(node_ids)}/$value"
5556
else:
5657
url = f"{BASE_URL}/{entity_type}({entity_id})/$value"
57-
response = requests.get(url, auth=auth, stream=True)
58-
59-
if response.status_code == 200:
60-
file_path = os.path.join(DOWNLOAD_DIR, f"{entity['Name']}")
61-
with open(file_path, "wb") as f:
62-
for chunk in response.iter_content(chunk_size=8192):
63-
f.write(chunk)
64-
logging.info(f"Downloaded {entity_type} {entity['Id']} to {file_path}")
65-
else:
66-
logging.error(f"Failed to download {entity_type} {entity['Id']} value: {response.status_code} {requests.status_codes._codes[response.status_code][0]}")
58+
59+
attempt = 0
60+
while attempt <= retries:
61+
response = requests.get(url, auth=auth, stream=True)
62+
63+
if response.status_code == 200:
64+
file_path = os.path.join(DOWNLOAD_DIR, f"{entity['Name']}")
65+
with open(file_path, "wb") as f:
66+
for chunk in response.iter_content(chunk_size=8192):
67+
f.write(chunk)
68+
logging.info(f"Downloaded {entity_type} {entity['Id']} to {file_path}")
69+
return # success, exit the function
70+
71+
elif response.status_code == 429:
72+
attempt += 1
73+
if attempt > retries:
74+
break
75+
wait_time = 20 * attempt # exponential backoff
76+
logging.warning(f"Received 429. Retrying in {wait_time} seconds... (Attempt {attempt}/{retries})")
77+
time.sleep(wait_time)
78+
else:
79+
break # don't retry on other status codes
80+
81+
logging.error(
82+
f"Failed to download {entity_type} {entity['Id']} value: "
83+
f"{response.status_code} {requests.status_codes._codes[response.status_code][0]}"
84+
)
6785

6886
def inspect_nodes(auth, product_id, node_id, depth=0, max_depth=1):
6987
"""Recursively explore Nodes and download some of their $value."""

0 commit comments

Comments
 (0)