Completed
Pull Request — master (#45)
by Paolo
06:21
created

samples.tasks.BatchDeleteSamples.on_failure()   A

Complexity

Conditions 1

Size

Total Lines 20
Code Lines 13

Duplication

Lines 20
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 13
dl 20
loc 20
rs 9.75
c 0
b 0
f 0
cc 1
nop 6
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
class BatchDeleteSamples(MyTask):
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 View Code Duplication
    def on_failure(self, exc, task_id, args, kwargs, einfo):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
31
        logger.error('{0!r} failed: {1!r}'.format(task_id, exc))
32
33
        # get submission object
34
        submission_obj = Submission.objects.get(pk=kwargs['submission_id'])
35
36
        # mark submission with ERROR
37
        submission_obj.status = ERROR
38
        submission_obj.message = (
39
            "Error in sample batch delete: %s" % (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 sample batch delete for submission: %s" % (
47
                submission_obj.id),
48
            ("Something goes wrong in batch delete for samples. Please report "
49
             "this to InjectTool team\n\n %s" % str(einfo)),
50
        )
51
52
        # TODO: submit mail to admin
53
54
    def run(self, submission_id, sample_ids):
55
        """Function for batch update attribute in animals
56
        Args:
57
            submission_id (int): id of submission
58
            sample_ids (list): set with ids to delete
59
        """
60
61
        # get a submisision object
62
        submission_obj = Submission.objects.get(pk=submission_id)
63
64
        logger.info("Start batch delete for samples")
65
        success_ids = list()
66
        failed_ids = list()
67
68
        for sample_id in sample_ids:
69
            try:
70
                name = Name.objects.get(
71
                    name=sample_id, submission=submission_obj)
72
73
                sample_obj = Sample.objects.get(name=name)
74
75
                with transaction.atomic():
76
                    sample_obj.delete()
77
                    name.delete()
78
                success_ids.append(sample_id)
79
80
            except Name.DoesNotExist:
81
                failed_ids.append(sample_id)
82
83
            except Sample.DoesNotExist:
84
                failed_ids.append(sample_id)
85
86
        # Update submission
87
        submission_obj.refresh_from_db()
88
        submission_obj.status = NEED_REVISION
89
90
        if len(failed_ids) != 0:
91
            submission_obj.message = f"You've removed {len(success_ids)} " \
92
                f"samples. It wasn't possible to find records with these " \
93
                f"ids: {', '.join(failed_ids)}. Rerun validation please!"
94
        else:
95
            submission_obj.message = f"You've removed {len(success_ids)} " \
96
                f"samples. Rerun validation please!"
97
98
        submission_obj.save()
99
100
        summary_obj, created = ValidationSummary.objects.get_or_create(
101
            submission=submission_obj, type='sample')
102
        summary_obj.reset_all_count()
103
104
        send_message(
105
            submission_obj, construct_validation_message(submission_obj)
106
        )
107
108
        logger.info("batch delete for samples completed")
109
110
        return 'success'
111
112
113
# register explicitly tasks
114
# https://github.com/celery/celery/issues/3744#issuecomment-271366923
115
celery_app.tasks.register(BatchDeleteSamples)
116