Hide keyboard shortcuts

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 

2import logging 

3from datetime import timedelta 

4from django.core.management.base import CommandParser 

5from django.utils.timezone import now 

6from jutil.command import SafeCommand 

7from jbank.ecb import download_euro_exchange_rates_xml, parse_euro_exchange_rates_xml 

8from jutil.format import format_xml 

9from jbank.models import CurrencyExchangeSource, CurrencyExchange 

10 

11 

12logger = logging.getLogger(__name__) 

13 

14 

15class 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( 

54 record_date=record_date, 

55 source_currency="EUR", 

56 unit_currency="EUR", 

57 target_currency=currency, 

58 exchange_rate=rate, 

59 source=source, 

60 )[1] 

61 if created and verbose: 

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

63 

64 if delete_old_date: 

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

66 for e in qs: 

67 try: 

68 e.delete() 

69 except Exception as err: 

70 logger.error("Failed to delete {}: {}".format(e, err))