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

48 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-27 13:36 +0700

1import logging 

2from datetime import timedelta 

3from django.core.management.base import CommandParser 

4from django.utils.timezone import now 

5from jutil.command import SafeCommand 

6from jbank.ecb import download_euro_exchange_rates_xml, parse_euro_exchange_rates_xml 

7from jutil.format import format_xml 

8from jbank.models import CurrencyExchangeSource, CurrencyExchange 

9 

10logger = logging.getLogger(__name__) 

11 

12 

13class 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)