-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch_spacex_images.py
80 lines (62 loc) · 2.29 KB
/
fetch_spacex_images.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
import requests
from argparse import ArgumentParser
from img_functions import download_image
from dotenv import load_dotenv
SPACEX_API_METHOD_URL = 'https://api.spacexdata.com/v5/launches'
def main():
load_dotenv()
arg_parser = ArgumentParser(
description='This program allows to download photos from SpaceX rocket launches.'
)
arg_parser.add_argument(
'-id',
'--launch_id',
help="ID of the SpaceX launch for which photos are to be downloaded. "
"By default uses the last SpaceX flight "
"for which photos were taken and uploaded to Flickr.",
default=get_last_flight_id()
)
args = arg_parser.parse_args()
flight_id = args.launch_id
images_path = os.getenv("IMAGES_PATH")
fetch_spacex_launch_photos(launch_id=flight_id, images_path=images_path)
def get_last_flight_id() -> str:
"""
This function retrieves the ID of the last SpaceX flight
for which photos were taken and uploaded to Flickr.
:return: None
"""
spacex_response = requests.get(SPACEX_API_METHOD_URL)
spacex_response.raise_for_status()
flights = spacex_response.json()
last_flight = None
for flight in reversed(flights):
if flight['links']['flickr']['original']:
last_flight = flight
break
return last_flight['id']
def fetch_spacex_launch_photos(launch_id: str, images_path: str):
"""
Downloads images of a specific SpaceX launch from the SpaceX API
and saves them to the local machine.
:param launch_id: ID of the SpaceX launch
:param images_path: path to a folder where images will be saved
:return: None
"""
spacex_response = requests.get(f"{SPACEX_API_METHOD_URL}/{launch_id}")
spacex_response.raise_for_status()
flight = spacex_response.json()
photo_links = flight['links']['flickr']['original']
if not photo_links:
raise PhotosMissingError
for i, link in enumerate(photo_links):
download_image(link, f"{images_path}/spaceX_{i}.jpg")
class PhotosMissingError(ValueError):
"""
Exception raised when no photos were taken for a SpaceX launch.
"""
def __init__(self, message="No photos were taken for this launch!"):
super().__init__(message)
if __name__ == "__main__":
main()