Skip to content

Commit b64fd56

Browse files
JDeepDcclauss
andauthored
Added feature to web_programming/nasa_data.py : Can download the APOD image to a specified location on disk. (#5551)
* Added a feature to download images. * Minor changes * Update nasa_data.py * : Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 27f2465 commit b64fd56

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

web_programming/nasa_data.py

+22-11
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,38 @@
1+
import shutil
2+
13
import requests
24

35

4-
def get_apod_data(api_key: str) -> dict:
6+
def get_apod_data(api_key: str, download: bool = False, path: str = ".") -> dict:
57
"""
68
Get the APOD(Astronomical Picture of the day) data
7-
Get the API Key from : https://api.nasa.gov/
9+
Get your API Key from: https://api.nasa.gov/
810
"""
9-
url = "https://api.nasa.gov/planetary/apod/"
11+
url = "https://api.nasa.gov/planetary/apod"
1012
return requests.get(url, params={"api_key": api_key}).json()
1113

1214

15+
def save_apod(api_key: str, path: str = ".") -> dict:
16+
apod_data = get_apod_data(api_key)
17+
img_url = apod_data["url"]
18+
img_name = img_url.split("/")[-1]
19+
response = requests.get(img_url, stream=True)
20+
21+
with open(f"{path}/{img_name}", "wb+") as img_file:
22+
shutil.copyfileobj(response.raw, img_file)
23+
del response
24+
return apod_data
25+
26+
1327
def get_archive_data(query: str) -> dict:
1428
"""
1529
Get the data of a particular query from NASA archives
1630
"""
17-
endpoint = "https://images-api.nasa.gov/search"
18-
return requests.get(endpoint, params={"q": query}).json()
31+
url = "https://images-api.nasa.gov/search"
32+
return requests.get(url, params={"q": query}).json()
1933

2034

2135
if __name__ == "__main__":
22-
print(get_apod_data("YOUR API KEY"))
23-
print(
24-
get_archive_data("apollo 2011")["collection"]["items"][0]["data"][0][
25-
"description"
26-
]
27-
)
36+
print(save_apod("YOUR API KEY"))
37+
apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"]
38+
print(apollo_2011_items[0]["data"][0]["description"])

0 commit comments

Comments
 (0)