From 79966429fe5b64c4796517a400b2bee4c2a0d11d Mon Sep 17 00:00:00 2001 From: Leonard Techel Date: Sat, 4 Jun 2022 13:55:58 +0200 Subject: [PATCH] feat(backend): Add cli command to import parameter qr codes from CSV --- backend/dpt_app/trails/management/__init__.py | 0 .../trails/management/commands/__init__.py | 0 .../management/commands/import-codes.py | 44 +++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 backend/dpt_app/trails/management/__init__.py create mode 100644 backend/dpt_app/trails/management/commands/__init__.py create mode 100644 backend/dpt_app/trails/management/commands/import-codes.py diff --git a/backend/dpt_app/trails/management/__init__.py b/backend/dpt_app/trails/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/dpt_app/trails/management/commands/__init__.py b/backend/dpt_app/trails/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/dpt_app/trails/management/commands/import-codes.py b/backend/dpt_app/trails/management/commands/import-codes.py new file mode 100644 index 0000000..f00002a --- /dev/null +++ b/backend/dpt_app/trails/management/commands/import-codes.py @@ -0,0 +1,44 @@ +import argparse +import csv +from django.core.management.base import BaseCommand, CommandError, CommandParser +from typing import Any, Optional + +from trails.enums import ActionType +from trails.qr_models import Code, Action + + +class Command(BaseCommand): + def add_arguments(self, parser: CommandParser) -> None: + parser.add_argument('csv', help='The CSV file', + type=argparse.FileType('r')) + + def handle(self, *args: Any, **options: Any) -> Optional[str]: + data = csv.reader(options['csv']) + + # first row is the header + header = next(data) + + if header != ['uuid', 'one_shot', 'name', 'parameter', 'parameter_value']: + raise CommandError('Header is not correct') + + for row in data: + # convert rows lists to dicts + row = dict(zip(header, row)) + + code, created = Code.objects.update_or_create( + uuid=row['uuid'], + defaults={ + 'uuid': row['uuid'], + 'one_shot': row['one_shot'] == '1', + 'name': row['name'] + } + ) + + Action.objects.update_or_create( + code=code, + defaults={ + 'action_type': ActionType.PARAMETER, + 'parameter': row['parameter'], + 'value': int(row['parameter_value']) + } + )