''' DS2500 Spring 2025 Sample code from class - reading in JSON data from a file, and from an API Goals for today: - read in JSON files for APOD and weather on mars - render the image, and print out the temps per Sol on Mars - Do the same thing with real-time data via the API ''' import json import requests from urllib.request import urlopen from PIL import Image import matplotlib.pyplot as plt APOD_FILE = "data/apod.json" WEATHER_FILE = "data/weather.json" APOD_URL = "https://api.nasa.gov/planetary/apod" API_KEY = "NTIKUHIONA8CJjtnHJfgMkHhy8wcLXfnIaDdN4oy" def display_img(url, title = ""): ''' given an image URL, render it in matplotlib ''' image = Image.open(urlopen(url)) plt.imshow(image) plt.axis("off") plt.title(title) plt.show() def create_page(filename, img_url, title = ""): ''' given a filename and an image URL, create a web page that displays it ''' html_content = (f"

Astronomy Pic

" f"
{title}") with open(filename, "w") as outfile: outfile.write(html_content) def read_json(filename): ''' given a filename, open and read and return as json ''' with open(filename, "r") as jfile: data = json.load(jfile) return data def request_api(url, params): ''' given a base url and a param dictionary, call the API function and return its json-formatted response ''' response = requests.get(url, params = params) return response.json() def print_weather_sols(weather_data): ''' given a dictionary with temp data for Mars, print out the av temp per sol ''' for key, val in weather_data.items(): if key.isdigit(): temp = val["AT"]["av"] print(f"Sol: {key}, temp: {temp}") def main(): # gather data - read in JSON files for pic apod_data = read_json(APOD_FILE) print(apod_data["url"]) # gather data - read in JSON file for weather # print out the av temp for each Sol weather_data = read_json(WEATHER_FILE) print_weather_sols(weather_data) # gather data in real-time from the APOD API params = {"api_key" : API_KEY, "date" : "2006-10-16"} apod_data = request_api(APOD_URL, params) # render the APOD image in a plot, and on a web page title = f"Astronomy Pic of the Day: {apod_data['date']}" display_img(apod_data["url"], title = title) create_page("planet.html", apod_data["url"], title) if __name__ == "__main__": main()