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

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

## 48 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1#pylint: disable=too-many-locals,too-many-branches,logging-format-interpolation

2 import logging

3 from datetime import timedelta

4 from django.core.management.base import CommandParser

5 from django.utils.timezone import now

6 from jutil.command import SafeCommand

7 from jbank.ecb import download_euro_exchange_rates_xml, parse_euro_exchange_rates_xml

8 from jutil.format import format_xml

9 from jbank.models import CurrencyExchangeSource, CurrencyExchange

10

11

12 logger = logging.getLogger(__name__)

13

14

15 class Command(SafeCommand):

16 help = """

17 Parses European Central Bank rates. Can use either pre-downloaded file or download from online (default).

18 """

19

20 def add_arguments(self, parser: CommandParser):

21 parser.add_argument('--file', type=str)

22 parser.add_argument('--verbose', action='store_true')

23 parser.add_argument('--xml-only', action='store_true')

24 parser.add_argument('--delete-older-than-days', type=int)

25

26 def do(self, *args, **options):

27 if options['file']:

28 with open(options['file'], 'rt') as fp:

29 content = fp.read()

30 else:

31 content = download_euro_exchange_rates_xml()

32

33 verbose = options['verbose']

34 if verbose or options['xml_only']:

35 print(format_xml(content))

36 if options['xml_only']:

37 return

38

39 rates = parse_euro_exchange_rates_xml(content)

40 if verbose:

41 for record_date, currency, rate in rates:

42 print(record_date, currency, rate)

43

44 delete_old_date = None

45 delete_old_days = options['delete_older_than_days']

46 if delete_old_days:

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

48

49 source, created = CurrencyExchangeSource.objects.get_or_create(name='European Central Bank')

50 for record_date, currency, rate in rates:

51 if delete_old_date and record_date < delete_old_date:

52 continue

53 created = CurrencyExchange.objects.get_or_create(record_date=record_date, source_currency='EUR', unit_currency='EUR',

54 target_currency=currency, exchange_rate=rate, source=source)[1]

55 if created and verbose:

56 print('({}, {}, {}) created'.format(record_date, currency, rate))

57

58 if delete_old_date:

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

60 for e in qs:

61 try:

62 e.delete()

63 except Exception as err:

64 logger.error('Failed to delete {}: {}'.format(e, err))