Last active
March 16, 2022 11:42
-
-
Save PiotrCzapla/074d8e73c6c12a66869918187e49b84d to your computer and use it in GitHub Desktop.
Get NBP currency exchange rate in python with memory cache, this can act as simple python API :)
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
# license: mit | |
import requests | |
from functools import lru_cache | |
@lru_cache(maxsize=None) | |
def get_nbp_exchange_rate(date:datetime, table='A'): | |
""" | |
Get the exchange rate from the NBP API, and store it in cache folder | |
>> get_nbp_exchange_rate(datetime(2022,3,8))['EUR'] | |
4.9121 | |
""" | |
url = 'http://api.nbp.pl/api/exchangerates/tables/{:s}/{:%Y-%m-%d}/?format=json'.format(table, date) | |
r = requests.get(url) | |
if r.status_code != 200: | |
raise RuntimeError("Unable to fetch exchange rate from NBP API") | |
return {rate['code']:rate['mid'] for rate in r.json()[0]['rates']} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment