Skip to content

Commit e6e9d71

Browse files
authored
Create Episode 05 - TTLcache with cachetools.py
1 parent 4d47969 commit e6e9d71

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# openexchange.py
2+
import requests
3+
from cachetools import cached, TTLCache
4+
5+
6+
class OpenExchangeClient:
7+
BASE_URL = 'https://openexchangerates.org/api'
8+
9+
def __init__(self, app_id):
10+
self.app_id = app_id
11+
12+
@property
13+
@cached(cache=TTLCache(maxsize=2, ttl=900)) # updates TTL - time to live cache
14+
def latest(self):
15+
return requests.get(f'{self.BASE_URL}/latest.json?app_id={self.app_id}').json()
16+
17+
def convert(self, from_amount, from_currency, to_currency):
18+
rates = self.latest['rates']
19+
to_rate = rates[to_currency]
20+
21+
if from_currency == 'USD':
22+
return from_amount * to_rate
23+
else:
24+
from_in_usd = from_amount / rates[from_currency]
25+
return from_in_usd * to_rate

0 commit comments

Comments
 (0)