aboutsummaryrefslogtreecommitdiff
path: root/ihatemoney/currency_convertor.py
diff options
context:
space:
mode:
authordark0dave <52840419+dark0dave@users.noreply.github.com>2020-04-29 21:57:08 +0100
committerGitHub <noreply@github.com>2020-04-29 22:57:08 +0200
commitf389c562595f74bea86e49c29949f4a7b0e78900 (patch)
treec3c0ac339ad002f47e2be9cd3a46d347012b1d70 /ihatemoney/currency_convertor.py
parent162193c787341118621b36b4c8933bbe8af092df (diff)
downloadihatemoney-mirror-f389c562595f74bea86e49c29949f4a7b0e78900.zip
ihatemoney-mirror-f389c562595f74bea86e49c29949f4a7b0e78900.tar.gz
ihatemoney-mirror-f389c562595f74bea86e49c29949f4a7b0e78900.tar.bz2
Feature/currencies (#541)
Now each project can have a currency, default to None. Each bill can use a different currency, and a conversion to project default currency is done on settle. Fix #512
Diffstat (limited to 'ihatemoney/currency_convertor.py')
-rw-r--r--ihatemoney/currency_convertor.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/ihatemoney/currency_convertor.py b/ihatemoney/currency_convertor.py
new file mode 100644
index 0000000..75fa834
--- /dev/null
+++ b/ihatemoney/currency_convertor.py
@@ -0,0 +1,46 @@
+from cachetools import TTLCache, cached
+import requests
+
+
+class Singleton(type):
+ _instances = {}
+
+ def __call__(cls, *args, **kwargs):
+ if cls not in cls._instances:
+ cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
+ return cls._instances[cls]
+
+
+class CurrencyConverter(object, metaclass=Singleton):
+ # Get exchange rates
+ default = "No Currency"
+ api_url = "https://api.exchangeratesapi.io/latest?base=USD"
+
+ def __init__(self):
+ pass
+
+ @cached(cache=TTLCache(maxsize=1, ttl=86400))
+ def get_rates(self):
+ rates = requests.get(self.api_url).json()["rates"]
+ rates[self.default] = 1.0
+ return rates
+
+ def get_currencies(self):
+ rates = [rate for rate in self.get_rates()]
+ rates.sort(key=lambda rate: "" if rate == self.default else rate)
+ return rates
+
+ def exchange_currency(self, amount, source_currency, dest_currency):
+ if (
+ source_currency == dest_currency
+ or source_currency == self.default
+ or dest_currency == self.default
+ ):
+ return amount
+
+ rates = self.get_rates()
+ source_rate = rates[source_currency]
+ dest_rate = rates[dest_currency]
+ new_amount = (float(amount) / source_rate) * dest_rate
+ # round to two digits because we are dealing with money
+ return round(new_amount, 2)