From 01a95201406fd222e45c6cf1cbc1520f3d497e5c Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Sat, 2 Mar 2019 22:40:47 +0100 Subject: [PATCH] add import_users script to import users from CSV with already hashed passwords --- .../core/management/commands/import_users.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 passbook/core/management/commands/import_users.py diff --git a/passbook/core/management/commands/import_users.py b/passbook/core/management/commands/import_users.py new file mode 100644 index 000000000..fc694ef96 --- /dev/null +++ b/passbook/core/management/commands/import_users.py @@ -0,0 +1,44 @@ +"""passbook import_users management command""" +from csv import DictReader +from logging import getLogger + +from django.core.management.base import BaseCommand +from django.core.validators import EmailValidator, ValidationError + +from passbook.core.models import User + +LOGGER = getLogger(__name__) + +class Command(BaseCommand): + """Import users from CSV file""" + + def add_arguments(self, parser): + # Positional arguments + parser.add_argument('file', nargs='+', type=str) + + def handle(self, *args, **options): + """Create Users from CSV file""" + for file in options.get('file'): + with open(file, 'r') as _file: + reader = DictReader(_file) + for user in reader: + LOGGER.debug('User %s', user.get('username')) + try: + # only import users with valid email addresses + if user.get('email'): + validator = EmailValidator() + validator(user.get('email')) + # use combination of username and email to check for existing user + if User.objects.filter( + username=user.get('username'), + email=user.get('email')).exists(): + LOGGER.debug('User %s exists already, skipping', user.get('username')) + # Create user + User.objects.create( + username=user.get('username'), + email=user.get('email'), + name=user.get('name')) + LOGGER.debug('Created User %s', user.get('username')) + except ValidationError as exc: + LOGGER.warning('User %s caused %r, skipping', user.get('username'), exc) + continue