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

samples.tasks   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 123
Duplicated Lines 21.95 %

Importance

Changes 0
Metric Value
wmc 7
eloc 62
dl 27
loc 123
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B BatchDeleteSamples.run() 0 57 6
A BatchDeleteSamples.on_failure() 27 27 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
        submission_id, sample_ids = args[0], args[1]
34
35
        logger.error(
36
            ("BatchDeleteAnimals called with submission_id: %s and "
37
             "sample_ids: %s" % (submission_id, sample_ids))
38
        )
39
40
        # get submission object
41
        submission_obj = Submission.objects.get(pk=submission_id)
42
43
        # mark submission with ERROR
44
        submission_obj.status = ERROR
45
        submission_obj.message = (
46
            "Error in sample batch delete: %s" % (str(exc)))
47
        submission_obj.save()
48
49
        send_message(submission_obj)
50
51
        # send a mail to the user with the stacktrace (einfo)
52
        submission_obj.owner.email_user(
53
            "Error in sample batch delete for submission: %s" % (
54
                submission_obj.id),
55
            ("Something goes wrong in batch delete for samples. Please report "
56
             "this to InjectTool team\n\n %s" % str(einfo)),
57
        )
58
59
        # TODO: submit mail to admin
60
61
    def run(self, submission_id, sample_ids):
62
        """Function for batch update attribute in animals
63
        Args:
64
            submission_id (int): id of submission
65
            sample_ids (list): set with ids to delete
66
        """
67
68
        # get a submisision object
69
        submission_obj = Submission.objects.get(pk=submission_id)
70
71
        logger.info("Start batch delete for samples")
72
        success_ids = list()
73
        failed_ids = list()
74
75
        for sample_id in sample_ids:
76
            try:
77
                name = Name.objects.get(
78
                    name=sample_id, submission=submission_obj)
79
80
                sample_obj = Sample.objects.get(name=name)
81
82
                with transaction.atomic():
83
                    sample_obj.delete()
84
                    name.delete()
85
                success_ids.append(sample_id)
86
87
            except Name.DoesNotExist:
88
                failed_ids.append(sample_id)
89
90
            except Sample.DoesNotExist:
91
                failed_ids.append(sample_id)
92
93
        # Update submission
94
        submission_obj.refresh_from_db()
95
        submission_obj.status = NEED_REVISION
96
97
        if len(failed_ids) != 0:
98
            submission_obj.message = f"You've removed {len(success_ids)} " \
99
                f"samples. It wasn't possible to find records with these " \
100
                f"ids: {', '.join(failed_ids)}. Rerun validation please!"
101
        else:
102
            submission_obj.message = f"You've removed {len(success_ids)} " \
103
                f"samples. Rerun validation please!"
104
105
        submission_obj.save()
106
107
        summary_obj, created = ValidationSummary.objects.get_or_create(
108
            submission=submission_obj, type='sample')
109
        summary_obj.reset_all_count()
110
111
        send_message(
112
            submission_obj, construct_validation_message(submission_obj)
113
        )
114
115
        logger.info("batch delete for samples completed")
116
117
        return 'success'
118
119
120
# register explicitly tasks
121
# https://github.com/celery/celery/issues/3744#issuecomment-271366923
122
celery_app.tasks.register(BatchDeleteSamples)
123