use bulk_create and transcation for importing user

This commit is contained in:
virusdefender 2017-11-24 22:26:56 +08:00
parent a1eed315b4
commit 7cc33d0701
2 changed files with 32 additions and 23 deletions

View File

@ -557,20 +557,25 @@ class AdminUserTest(APITestCase):
def test_import_users(self): def test_import_users(self):
data = {"users": [["user1", "pass1", "eami1@e.com"], data = {"users": [["user1", "pass1", "eami1@e.com"],
["user1", "pass1", "eami1@e.com"], ["user2", "pass3", "eamil3@e.com"]]
["user2", "pass2"], ["user3", "pass3", "eamil3@e.com"]]
} }
resp = self.client.post(self.url, data) resp = self.client.post(self.url, data)
self.assertSuccess(resp) self.assertSuccess(resp)
self.assertDictEqual(resp.data["data"], {"omitted_count": 1,
"created_count": 2,
"get_count": 1})
# successfully created 2 users # successfully created 2 users
self.assertEqual(User.objects.all().count(), 4) self.assertEqual(User.objects.all().count(), 4)
def test_import_duplicate_user(self):
data = {"users": [["user1", "pass1", "eami1@e.com"],
["user1", "pass1", "eami1@e.com"]]
}
resp = self.client.post(self.url, data)
self.assertFailed(resp, "DETAIL: Key (username)=(user1) already exists.")
# no user is created
self.assertEqual(User.objects.all().count(), 2)
def test_delete_users(self): def test_delete_users(self):
self.test_import_users() self.test_import_users()
user_ids = User.objects.filter(username__in=["user1", "user3"]).values_list("id", flat=True) user_ids = User.objects.filter(username__in=["user1", "user2"]).values_list("id", flat=True)
user_ids = ",".join([str(id) for id in user_ids]) user_ids = ",".join([str(id) for id in user_ids])
resp = self.client.delete(self.url + "?id=" + user_ids) resp = self.client.delete(self.url + "?id=" + user_ids)
self.assertSuccess(resp) self.assertSuccess(resp)

View File

@ -1,8 +1,11 @@
import os import os
import re import re
import xlsxwriter import xlsxwriter
from django.db import transaction, IntegrityError
from django.db.models import Q from django.db.models import Q
from django.http import HttpResponse from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
from submission.models import Submission from submission.models import Submission
from utils.api import APIView, validate_serializer from utils.api import APIView, validate_serializer
@ -18,26 +21,27 @@ class UserAdminAPI(APIView):
@validate_serializer(ImportUserSeralizer) @validate_serializer(ImportUserSeralizer)
@super_admin_required @super_admin_required
def post(self, request): def post(self, request):
"""
Generate user
"""
data = request.data["users"] data = request.data["users"]
omitted_count = created_count = get_count = 0
user_list = []
for user_data in data: for user_data in data:
if len(user_data) != 3 or len(user_data[0]) > 32: if len(user_data) != 3 or len(user_data[0]) > 32:
omitted_count += 1 return self.error(f"Error occurred while processing data '{user_data}'")
continue user_list.append(User(username=user_data[0], password=make_password(user_data[1]), email=user_data[2]))
user, created = User.objects.get_or_create(username=user_data[0])
user.set_password(user_data[1]) try:
user.email = user_data[2] with transaction.atomic():
user.save() ret = User.objects.bulk_create(user_list)
if created: UserProfile.objects.bulk_create([UserProfile(user=user) for user in ret])
UserProfile.objects.create(user=user) return self.success()
created_count += 1 except IntegrityError as e:
else: # Extract detail from exception message
get_count += 1 # duplicate key value violates unique constraint "user_username_key"
return self.success({ # DETAIL: Key (username)=(root11) already exists.
"omitted_count": omitted_count, return self.error(str(e).split("\n")[1])
"created_count": created_count,
"get_count": get_count
})
@validate_serializer(EditUserSerializer) @validate_serializer(EditUserSerializer)
@super_admin_required @super_admin_required