Completed
Pull Request — master (#41)
by
unknown
05:50
created

animals.tasks.BatchUpdateAnimals.run()   A

Complexity

Conditions 2

Size

Total Lines 23
Code Lines 16

Duplication

Lines 23
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 16
dl 23
loc 23
rs 9.6
c 0
b 0
f 0
cc 2
nop 4
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Created on Wed Feb 27 16:38:37 2019
5
6
@author: Paolo Cozzi <[email protected]>
7
"""
8
9
from celery.utils.log import get_task_logger
10
import asyncio
11
12
from common.constants import ERROR, LOADED, STATUSES
13
from common.helpers import send_message_to_websocket
14
from image.celery import app as celery_app, MyTask
15
from image_app.models import Animal, Submission
16
from submissions.helpers import send_message
17
from validation.helpers import construct_validation_message
18
19
# Get an instance of a logger
20
logger = get_task_logger(__name__)
21
22
23 View Code Duplication
class BatchUpdateAnimals(MyTask):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
24
    name = "Batch update animals"
25
    description = """Batch update of field in animals"""
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 update for animals: %s"
39
                                  % (str(exc)))
40
        submission_obj.save()
41
42
        asyncio.get_event_loop().run_until_complete(
43
            send_message_to_websocket(
44
                {
45
                    'message': STATUSES.get_value_display(ERROR),
46
                    'notification_message': submission_obj.message
47
                },
48
                args[0]
49
            )
50
        )
51
52
        # send a mail to the user with the stacktrace (einfo)
53
        submission_obj.owner.email_user(
54
            "Error in batch update for animals: %s" % (args[0]),
55
            ("Something goes wrong  in batch update for animals. 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, animal_ids, attribute):
62
        """a function to upload data into UID"""
63
64
        logger.info(submission_id)
65
        logger.info(animal_ids)
66
        logger.info(attribute)
67
        logger.info("Start batch update for animals")
68
69
        for animal_id, value in animal_ids.items():
70
            animal = Animal.objects.get(pk=animal_id)
71
            setattr(animal, attribute, value)
72
            animal.save()
73
74
        # Update submission
75
        submission_obj = Submission.objects.get(pk=submission_id)
76
        submission_obj.status = LOADED
77
        submission_obj.message = "Data updated, try to rerun validation"
78
        submission_obj.save()
79
80
        send_message(
81
            submission_obj, construct_validation_message(submission_obj)
82
        )
83
        return 'success'
84
85
86
# register explicitly tasks
87
# https://github.com/celery/celery/issues/3744#issuecomment-271366923
88
celery_app.tasks.register(BatchUpdateAnimals)
89