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

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

## 49 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,logging-format-interpolation,too-many-branches

2 import json

3 import logging

4 import os

5 import zipfile

6 from random import randint

7 from django.conf import settings

8 from django.core.management.base import CommandParser

9 from django.utils.timezone import now

10 from jutil.command import SafeCommand

11 from jbank.models import WsEdiConnection

12

13

14 logger = logging.getLogger(__name__)

15

16

17 class Command(SafeCommand):

18 help = "Import WS-EDI connection"

19

20 def add_arguments(self, parser: CommandParser):

21 parser.add_argument("file", type=str)

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

23

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

25 zf = zipfile.ZipFile(options["file"])

26 ws_data = {}

27 today = now()

28

29 for filename in zf.namelist():

30 assert isinstance(filename, str)

31 if options["verbose"]:

32 print("Importing {}".format(filename))

33 if filename.endswith(".json"):

34 content = zf.read(filename)

35 ws_data = json.loads(content.decode())

36

37 pem_suffix = "-import-{}-{}.pem".format(today.date().isoformat(), randint(100, 999))

38 for filename in zf.namelist():

39 assert isinstance(filename, str)

40 if filename.endswith(".pem"):

41 content = zf.read(filename)

42 new_filename = filename[:-4] + pem_suffix

43 new_path = "certs/{}".format(new_filename)

44 with open(os.path.join(settings.MEDIA_ROOT, new_path), "wb") as fp:

45 fp.write(content) # pytype: disable=not-callable

46 repl = []

47 for k, v in ws_data.items():

48 if k.endswith("_file") and os.path.basename(v) == filename:

49 repl.append((k, new_path))

50 for k, v in repl:

51 ws_data[k] = v

52

53 if not ws_data:

54 print("Nothing to import!")

55 return

56 if "created" in ws_data:

57 del ws_data["created"]

58 ws = WsEdiConnection.objects.create(**ws_data)

59 logger.info("WsEdiConnection id={} created".format(ws.id))