Skip to content

Commit cce04b5

Browse files
authored
refactor: improve code structure with response validation function
Refactored the script to improve modularity and readability. - Moved image validation logic to a separate function `is_valid_image_response` - Keeps `fetch_image` function focused on download and file saving - Prepares the script for future enhancements and better testability
1 parent 0d4c533 commit cce04b5

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

ubuntu_image_fetcher.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,27 @@
22
import requests
33
from urllib.parse import urlparse
44

5+
MAX_FILE_SIZE = 10_000_000 # 10MB
6+
7+
def is_valid_image_response(response):
8+
content_type = response.headers.get("Content-Type", "")
9+
if not content_type.startswith("image/"):
10+
print(f"✗ Skipped: Not an image ({content_type})")
11+
return False
12+
13+
content_length = response.headers.get("Content-Length")
14+
if content_length and int(content_length) > MAX_FILE_SIZE:
15+
print(f"✗ Skipped: Image too large ({int(content_length)/1_000_000:.2f} MB)")
16+
return False
17+
18+
return True
19+
520
def fetch_image(image_url):
621
try:
722
response = requests.get(image_url, timeout=10)
823
response.raise_for_status()
924

10-
# Check if Content-Type is image/*
11-
content_type = response.headers.get("Content-Type", "")
12-
if not content_type.startswith("image/"):
13-
print(f"✗ Skipped: URL does not point to an image ({content_type})")
14-
return
15-
16-
# Optional: Check for large files (>10MB for example)
17-
content_length = response.headers.get("Content-Length")
18-
if content_length and int(content_length) > 10_000_000:
19-
print(f"✗ Skipped: Image too large ({int(content_length)/1_000_000:.2f} MB)")
25+
if not is_valid_image_response(response):
2026
return
2127

2228
parsed = urlparse(image_url)
@@ -37,6 +43,4 @@ def fetch_image(image_url):
3743
except requests.exceptions.RequestException as e:
3844
print(f"✗ Failed to fetch image: {e}")
3945
except Exception as e:
40-
print(f"✗ Unexpected error: {e}")
41-
42-
de
46+
print(f"✗ Un

0 commit comments

Comments
 (0)