#!/usr/bin/env python3 # # spotprices # # Copyright (C) 2021 # Paul E. Jones # # This program will connect to Packetizer's Precious Metal Spot Prices Service # and display the current spot prices. # import json import urllib.request # Define the URL for querying precious metal spot prices SPOT_METAL_PRICES = "https://services.packetizer.com/spotprices/?f=json" def create_error_string(error_string): """ Common routine to print errors """ return "An error occurred trying to get spot prices: {}".format(error_string) def get_spot_prices(url): """ Routine to query the precious metal spot prices from the given URL. If the error string has a zero-length, then the results can be found in the returned spot_prices dictionary """ error_string = "" spot_prices = {} try: resource = urllib.request.urlopen(url) if resource.status == 200: spot_prices = json.loads(resource.read()) else: error_string = create_error_string("Unexpected HTTP response is {}".format(resource.status.code)) except urllib.error.URLError as error: error_string = create_error_string("{}".format(str(error))) spot_prices = {} except json.JSONDecodeError: error_string = create_error_string("could not parse JSON response") spot_prices = {} except Exception as error: error_string = create_error_string("{}".format(str(error))) spot_prices = {} return spot_prices, error_string def main(): """ Main routine """ spot_prices, error_string = get_spot_prices(SPOT_METAL_PRICES) if len(error_string) > 0: print(error_string) elif len(spot_prices) >= 3: print("Gold: {}".format(spot_prices["gold"])) print("Silver: {}".format(spot_prices["silver"])) print("Platinum: {}".format(spot_prices["platinum"])) else: print("Could not get spot metal prices") if __name__ == "__main__": main()