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

animals.tasks.BatchDeleteAnimals.run()   B

Complexity

Conditions 7

Size

Total Lines 72
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 72
rs 7.472
c 0
b 0
f 0
cc 7
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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, Animal, 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 BatchDeleteAnimals(MyTask):
24
    name = "Batch delete animals"
25
    description = """Batch remove animals and associated 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 animal 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 animal batch delete for submission: %s" % (
47
                submission_obj.id),
48
            ("Something goes wrong in batch delete for animals. 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, animal_ids):
55
        """Function for batch update attribute in animals
56
        Args:
57
            submission_id (int): id of submission
58
            animal_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 animals")
65
        success_ids = list()
66
        failed_ids = list()
67
68
        for animal_id in animal_ids:
69
            try:
70
                name = Name.objects.get(
71
                    name=animal_id, submission=submission_obj)
72
73
                animal_object = Animal.objects.get(name=name)
74
                samples = animal_object.sample_set.all()
75
76
                with transaction.atomic():
77
                    for sample in samples:
78
                        sample_name = sample.name
79
                        sample.delete()
80
                        sample_name.delete()
81
82
                    logger.debug("Clearing all childs from this animal")
83
                    name.mother_of.clear()
84
                    name.father_of.clear()
85
86
                    # delete this animal object
87
                    logger.debug(
88
                        "Deleting animal:%s and name:%s" % (
89
                            animal_object, name))
90
                    animal_object.delete()
91
                    name.delete()
92
93
                success_ids.append(animal_id)
94
95
            except Name.DoesNotExist:
96
                failed_ids.append(animal_id)
97
98
            except Animal.DoesNotExist:
99
                failed_ids.append(animal_id)
100
101
        # Update submission
102
        submission_obj.refresh_from_db()
103
        submission_obj.status = NEED_REVISION
104
105
        if len(failed_ids) != 0:
106
            submission_obj.message = f"You've removed {len(success_ids)} " \
107
                f"animals. It wasn't possible to find records with these " \
108
                f"ids: {', '.join(failed_ids)}. Rerun validation please!"
109
        else:
110
            submission_obj.message = f"You've removed {len(success_ids)} " \
111
                f"animals. Rerun validation please!"
112
113
        submission_obj.save()
114
115
        summary_obj, created = ValidationSummary.objects.get_or_create(
116
            submission=submission_obj, type='animal')
117
        summary_obj.reset_all_count()
118
119
        send_message(
120
            submission_obj, construct_validation_message(submission_obj)
121
        )
122
123
        logger.info("batch delete for animals completed")
124
125
        return 'success'
126
127
128
# register explicitly tasks
129
# https://github.com/celery/celery/issues/3744#issuecomment-271366923
130
celery_app.tasks.register(BatchDeleteAnimals)
131