Coverage for jbank/management/commands/parse_ecb_rates.py: 0%

1 import logging

2 from datetime import timedelta

3 from django.core.management.base import CommandParser

4 from django.utils.timezone import now

5 from jutil.command import SafeCommand

6 from jbank.ecb import download_euro_exchange_rates_xml, parse_euro_exchange_rates_xml

7 from jutil.format import format_xml

8 from jbank.models import CurrencyExchangeSource, CurrencyExchange

9

10 logger = logging.getLogger(__name__)

11

12

13 class Command(SafeCommand):

14 help = "Parses European Central Bank exchange rates. Can use either pre-downloaded file or download from online (default)."

15

16 def add_arguments(self, parser: CommandParser):

17 parser.add_argument("--file", type=str)

18 parser.add_argument("--verbose", action="store_true")

19 parser.add_argument("--xml-only", action="store_true")

20 parser.add_argument("--delete-older-than-days", type=int)

21

22 def do(self, *args, **options): # pylint: disable=too-many-branches,too-many-locals

23 if options["file"]:

24 with open(options["file"], "rt", encoding="utf-8") as fp:

25 content = fp.read()

26 else:

27 content = download_euro_exchange_rates_xml()

28

29 verbose = options["verbose"]

30 if verbose or options["xml_only"]:

31 print(format_xml(content))

32 if options["xml_only"]:

33 return

34

35 rates = parse_euro_exchange_rates_xml(content)

36 if verbose:

37 for record_date, currency, rate in rates:

38 print(record_date, currency, rate)

39

40 delete_old_date = None

41 delete_old_days = options["delete_older_than_days"]

42 if delete_old_days:

43 delete_old_date = now().date() - timedelta(days=delete_old_days)

44

45 source, created = CurrencyExchangeSource.objects.get_or_create(name="European Central Bank")

46 for record_date, currency, rate in rates:

47 if delete_old_date and record_date < delete_old_date:

48 continue

49 created = CurrencyExchange.objects.get_or_create(

50 record_date=record_date,

51 source_currency="EUR",

52 unit_currency="EUR",

53 target_currency=currency,

54 exchange_rate=rate,

55 source=source,

56 )[1]

57 if created and verbose:

58 print("({}, {}, {}) created".format(record_date, currency, rate))

59

60 if delete_old_date:

61 qs = CurrencyExchange.objects.filter(record_date__lt=delete_old_date, recorddetail_set=None)

62 for e in qs:

63 try:

64 e.delete()

65 except Exception as err:

66 logger.error("Failed to delete %s: %s", e, err)