Created
April 29, 2020 22:23
-
-
Save numpde/1a95a6fee5700269d985eada77691983 to your computer and use it in GitHub Desktop.
Download exchange rates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# RA, 2020-04-30 | |
# Download exchange rates -- template | |
import json | |
import urllib.request | |
from retry import retry | |
from pathlib import Path | |
@retry(Exception, tries=2) | |
def get_exchange_rates(symbols: set, base="USD", path=Path("rates.txt")): | |
""" | |
Download exchange rates or load from file if existent | |
""" | |
try: | |
# Use the old rates file, if available | |
# Note: delete the file to update the exchange rates | |
rates = json.load(path.open(mode='r')) | |
except (json.decoder.JSONDecodeError, FileNotFoundError): | |
# Re-download the exchange rates | |
url = "https://api.exchangeratesapi.io/latest?symbols={symbols}&base={base}" | |
url = url.format(symbols=(",".join(symbols)), base=base) | |
data = urllib.request.urlopen(url).read().decode() | |
# The data has the following format: | |
# rates = {"rates": {"CHF": 0.9750046117, "EUR": 0.9223390518}, "base": "USD", "date": "2020-04-29"} | |
rates = json.loads(data) | |
json.dump(rates, path.open(mode='w')) | |
return rates['rates'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment