Completed
Pull Request — master (#97)
by Paolo
08:19 queued 06:36
created

Command.handle()   B

Complexity

Conditions 5

Size

Total Lines 63
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 35
dl 0
loc 63
rs 8.5733
c 0
b 0
f 0
cc 5
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 Tue May 26 17:21:28 2020
5
6
@author: Paolo Cozzi <[email protected]>
7
"""
8
9
import logging
10
11
import pyUSIrest.usi
12
import pyUSIrest.exceptions
13
14
from django.core.management import BaseCommand
15
16
from biosample.helpers import get_manager_auth
17
from biosample.models import OrphanSubmission
18
from biosample.tasks.cleanup import get_orphan_samples
19
from common.constants import SUBMITTED, ERROR
20
21
# Get an instance of a logger
22
logger = logging.getLogger(__name__)
23
24
25
def create_biosample_submission(root, team):
26
    logger.debug("Creating a new submission")
27
28
    usi_team = root.get_team_by_name(team.name)
29
    usi_submission = usi_team.create_submission()
30
31
    submission = OrphanSubmission(
32
        usi_submission_name=usi_submission.name)
33
    submission.save()
34
35
    logger.debug("Created submission '%s' for '%s'" % (submission, team.name))
36
    return usi_submission, submission
37
38
39
def update_submission_status(submission):
40
    """Set SUBMITTED status to submission"""
41
42
    # update submission status
43
    if submission:
44
        submission.status = SUBMITTED
45
        submission.save()
46
47
48
class Command(BaseCommand):
49
    help = 'Get a JSON for biosample submission'
50
51
    def add_arguments(self, parser):
52
53
        parser.add_argument(
54
            '--limit',
55
            required=False,
56
            help="Limit to LIMIT items",
57
            default=None,
58
            type=int)
59
60
    def handle(self, *args, **options):
61
        # call commands and fill tables.
62
        logger.info("Called patch_orphan_samples")
63
64
        # get a new auth object
65
        auth = get_manager_auth()
66
67
        # get a new root object
68
        root = pyUSIrest.usi.Root(auth)
69
70
        # some variables
71
        count = 1
72
        old_team = None
73
        usi_submission = None
74
        submission = None
75
76
        # iterate among orphan sample, create a BioSample submission
77
        # and then add biosample for patch
78
        for record in get_orphan_samples(limit=options['limit']):
79
            (data, team, sample) = (
80
                record['data'], record['team'], record['sample'])
81
82
            if count % 100 == 0 or old_team != team:
83
                update_submission_status(submission)
84
85
                # create a new Biosample submission
86
                usi_submission, submission = create_biosample_submission(
87
                    root, team)
88
89
                # reset count and old_team
90
                count = 1
91
                old_team = team
92
93
            # add sample to submission
94
            try:
95
                logger.info("Submitting '%s'" % data['accession'])
96
                usi_submission.create_sample(data)
97
98
            except pyUSIrest.exceptions.USIDataError as error:
99
                logger.error(
100
                    "Can't remove '%s': Error was '%s'" % (
101
                        data['accession'], str(error)))
102
                sample.status = ERROR
103
                sample.save()
104
                continue
105
106
            # update sample status and track submission
107
            sample.status = SUBMITTED
108
            sample.submission = submission
109
            sample.save()
110
111
            # update submission count
112
            submission.samples_count = count
113
            submission.save()
114
115
            # new element
116
            count += 1
117
118
        # update the last submission status
119
        update_submission_status(submission)
120
121
        # end the script
122
        logger.info("patch_orphan_samples ended")
123