Completed
Push — master ( 662541...bf152a )
by Edward
18s
created

GetScanExecutions()   C

Complexity

Conditions 9

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 9
dl 0
loc 57
rs 5.2182

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
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import requests
17
from datetime import datetime
18
19
20
def GetScanExecutions(config, scan_id):
21
    """
22
    The template class for
23
24
    Returns: An blank Dict.
25
26
    Raises:
27
    ValueError: On lack of key in config.
28
    """
29
    results = {}
30
31
    url = "https://{}/api/scan/v1/scans/{}".format(config['api_host'], scan_id)
32
    headers = {"Accept": "application/json"}
33
34
    try:
35
        r = requests.get(url,
36
                         headers=headers,
37
                         auth=(config['api_key'], ''))
38
        r.raise_for_status()
39
    except:
40
        raise ValueError("HTTP error: %s on %s" % (r.status_code, r.url))
41
42
    try:
43
        data = r.json()
44
    except:
45
        raise ValueError("Invalid JSON")
46
    else:
47
        results = {'latest_complete': None, 'scans': []}
48
        for item in data:
49
            cd = datetime.fromtimestamp(item['create_date'])
50
            create_date = cd.strftime('%Y-%m-%d %H:%M:%S')
51
52
            if item['finish_date'] is not None:
53
                fd = datetime.fromtimestamp(item['finish_date'])
54
                finish_date = fd.strftime('%Y-%m-%d %H:%M:%S')
55
                duration = str(fd - cd)
56
            else:
57
                finish_date = "-"
58
                duration = str(datetime.now().replace(microsecond=0) - cd)
59
60
            results['scans'].append({"id": item['id'],
61
                                     "active": item['active'],
62
                                     "create_date": create_date,
63
                                     "finish_date": finish_date,
64
                                     "duration": duration})
65
66
    # This list can be very large, limit to the last 10.
67
    results['scans'].sort(reverse=True)
68
    results['scans'] = results['scans'][0:10]
69
70
    # Find the latest ccmpleted scan..
71
    for item in results['scans']:
72
        if item['active'] is False:
73
            results['latest_complete'] = item['id']
74
            break
75
76
    return results
77