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

39 statements  

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

1import json 

2import os 

3import zipfile 

4from datetime import datetime, date 

5from django.conf import settings 

6from django.core.management.base import CommandParser 

7from jutil.command import SafeCommand 

8from jbank.models import WsEdiConnection 

9 

10 

11class Command(SafeCommand): 

12 help = "Export WS-EDI connection" 

13 

14 def add_arguments(self, parser: CommandParser): 

15 parser.add_argument("ws", type=int) 

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

17 

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

19 ws = WsEdiConnection.objects.all().get(id=options["ws"]) 

20 assert isinstance(ws, WsEdiConnection) 

21 

22 filename = "ws{}.zip".format(ws.id) 

23 if options["file"]: 

24 filename = options["file"] 

25 

26 files = [] 

27 ws_data = {} 

28 for k, v in ws.__dict__.items(): 

29 if not k.startswith("_") and k != "id": 

30 if isinstance(v, datetime): 

31 v = v.isoformat() 

32 elif isinstance(v, date): 

33 v = v.isoformat() 

34 ws_data[k] = v 

35 if k.endswith("_file") and v: 

36 files.append(os.path.join(settings.MEDIA_ROOT, v)) 

37 

38 zf = zipfile.ZipFile(filename, "w", zipfile.ZIP_DEFLATED) # noqa 

39 json_str = json.dumps(ws_data, indent=4) 

40 print("Adding file ws.json:", json_str) 

41 zf.writestr("ws.json", json_str) 

42 for file in files: 

43 print("Adding file", file) 

44 zf.write(file, os.path.basename(file)) 

45 zf.close() 

46 print(filename, "written")