Passed
Pull Request — master (#45)
by Paolo
05:45
created

samples.tasks.BatchDeleteSamples.run()   B

Complexity

Conditions 6

Size

Total Lines 43
Code Lines 28

Duplication

Lines 43
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 28
dl 43
loc 43
rs 8.2746
c 0
b 0
f 0
cc 6
nop 3
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Created on Wed Feb 27 16:38:37 2019
5
@author: Paolo Cozzi <[email protected]>
6
"""
7
8
from celery.utils.log import get_task_logger
9
10
from django.db import transaction
11
12
from common.constants import ERROR, NEED_REVISION
13
from image.celery import app as celery_app, MyTask
14
from image_app.models import Submission, Sample, Name
15
from submissions.helpers import send_message
16
from validation.helpers import construct_validation_message
17
from validation.models import ValidationSummary
18
19
# Get an instance of a logger
20
logger = get_task_logger(__name__)
21
22
23 View Code Duplication
class BatchDeleteSamples(MyTask):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
24
    name = "Batch delete samples"
25
    description = """Batch remove samples"""
26
27
    # Ovverride default on failure method
28
    # This is not a failed validation for a wrong value, this is an
29
    # error in task that mean an error in coding
30
    def on_failure(self, exc, task_id, args, kwargs, einfo):
31
        logger.error('{0!r} failed: {1!r}'.format(task_id, exc))
32
33
        # get submission object
34
        submission_obj = Submission.objects.get(pk=args[0])
35
36
        # mark submission with ERROR
37
        submission_obj.status = ERROR
38
        submission_obj.message = ("Error in batch delete for samples: %s"
39
                                  % (str(exc)))
40
        submission_obj.save()
41
42
        send_message(submission_obj)
43
44
        # send a mail to the user with the stacktrace (einfo)
45
        submission_obj.owner.email_user(
46
            "Error in batch delete for samples: %s" % (args[0]),
47
            ("Something goes wrong in batch delete for samples. Please report "
48
             "this to InjectTool team\n\n %s" % str(einfo)),
49
        )
50
51
        # TODO: submit mail to admin
52
53
    def run(self, submission_id, sample_ids):
54
        """Function for batch update attribute in animals
55
        Args:
56
            submission_id (int): id of submission
57
            sample_ids (list): set with ids to delete
58
        """
59
60
        logger.info("Start batch delete for samples")
61
        success_ids = list()
62
        failed_ids = list()
63
        for sample_id in sample_ids:
64
            try:
65
                name = Name.objects.get(name=sample_id)
66
                object = Sample.objects.get(name=name)
67
                with transaction.atomic():
68
                    object.delete()
69
                    name.delete()
70
                success_ids.append(sample_id)
71
            except Name.DoesNotExist:
72
                failed_ids.append(sample_id)
73
            except Sample.DoesNotExist:
74
                failed_ids.append(sample_id)
75
        # Update submission
76
        submission_obj = Submission.objects.get(pk=submission_id)
77
        submission_obj.status = NEED_REVISION
78
        if len(failed_ids) != 0:
79
            submission_obj.message = f"You've removed {len(success_ids)} " \
80
                f"samples. It wasn't possible to find records with these ids:" \
81
                f" {', '.join(failed_ids)}. Rerun validation please!"
82
        else:
83
            submission_obj.message = f"You've removed {len(success_ids)} " \
84
                f"samples. Rerun validation please!"
85
        submission_obj.save()
86
87
        summary_obj, created = ValidationSummary.objects.get_or_create(
88
            submission=submission_obj, type='sample')
89
        summary_obj.reset_all_count()
90
91
        send_message(
92
            submission_obj, construct_validation_message(submission_obj)
93
        )
94
95
        return 'success'
96
97
98
# register explicitly tasks
99
# https://github.com/celery/celery/issues/3744#issuecomment-271366923
100
celery_app.tasks.register(BatchDeleteSamples)
101