Skip to content

Instantly share code, notes, and snippets.

@Santiago-j-s
Last active August 19, 2020 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Santiago-j-s/5382001360a3709f69691f2f56dcd96e to your computer and use it in GitHub Desktop.
Save Santiago-j-s/5382001360a3709f69691f2f56dcd96e to your computer and use it in GitHub Desktop.
# coding: utf-8
import requests
import datetime
API_KEY = '' # Get a free API KEY on https://api.nasa.gov/
URL = 'https://api.nasa.gov/planetary/apod'
START = datetime.date(2019, 1, 1)
END = datetime.date.today()
IMGS_FOLDER = 'imgs'
ERROR_FILE = 'apod_errors.txt'
def print_data(data: str, filename: str):
with open(ERROR_FILE, 'a') as f:
print(data, file=f)
def write_file(img_url: str, filename: str):
r = requests.get(img_url, stream=True)
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=512*1024):
f.write(chunk)
delta = datetime.timedelta(days=1)
date = START
while date < END:
date = date + delta
d = date.strftime(r'%Y-%m-%d')
img_url = f"{URL}?api_key={API_KEY}&date={d}"
data = requests.get(img_url).json()
if data['media_type'] == 'image':
try:
filename = d + '-' + data['hdurl'].split('/')[-1]
write_file(data['hdurl'], '/'.join([IMGS_FOLDER, filename]))
except KeyError as e:
print_data(data, ERROR_FILE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment