Create currency exchange rate module
This commit is contained in:
commit
0d2d9a491a
4 changed files with 43 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
0
__init__.py
Normal file
0
__init__.py
Normal file
32
helpers.py
Normal file
32
helpers.py
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
from core.classes.http import HTTP
|
||||||
|
from core.models.local import Currency
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from logging import getLogger
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
logger = getLogger(__name__)
|
||||||
|
|
||||||
|
def update_currencies(currencies=[]):
|
||||||
|
data = HTTP("https://api.ratesapi.io/api/latest").data
|
||||||
|
loaded = json.loads(data)
|
||||||
|
base = Currency.get_base().code
|
||||||
|
|
||||||
|
if (not base == loaded["base"]) and (not base in loaded["rates"].keys()):
|
||||||
|
raise ValueError(f"Base currency {base} not supported.")
|
||||||
|
|
||||||
|
rates = {loaded["base"]: Decimal(1 if base == loaded["base"] else loaded["rates"][base])}
|
||||||
|
|
||||||
|
for currency, rate in loaded["rates"].items():
|
||||||
|
rates[currency] = Decimal(1) if base == currency else rates[loaded["base"]] / Decimal(rate)
|
||||||
|
|
||||||
|
for currency in Currency.objects.all():
|
||||||
|
if (not currencies) or (currency.code in currencies):
|
||||||
|
if currency.code in rates.keys():
|
||||||
|
currency.rate = rates[currency.code]
|
||||||
|
currency.save()
|
||||||
|
logger.info(f"Updated exchange rate for {currency.code}")
|
||||||
|
else:
|
||||||
|
logger.warn(f"Unable to set exchange rate for {currency.code} - currency not supported.")
|
||||||
|
|
9
management/commands/updateforex.py
Normal file
9
management/commands/updateforex.py
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
from django.core.management.base import BaseCommand, CommandError
|
||||||
|
|
||||||
|
from ratesapi.helpers import update_currencies
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = 'Updates exchange rates for all supported currencies'
|
||||||
|
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
update_currencies()
|
Loading…
Reference in a new issue