Passed
Push — master ( c6068e...54bd3b )
by Guangyu
02:21 queued 10s
created

equipmenttracking.Reporting.on_get()   F

Complexity

Conditions 17

Size

Total Lines 81
Code Lines 48

Duplication

Lines 81
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 48
dl 81
loc 81
rs 1.8
c 0
b 0
f 0
cc 17
nop 2

How to fix   Long Method    Complexity   

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:

Complexity

Complex classes like equipmenttracking.Reporting.on_get() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from anytree import Node, AnyNode, LevelOrderIter
6
7
8 View Code Duplication
class Reporting:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
9
    @staticmethod
10
    def __init__():
11
        pass
12
13
    @staticmethod
14
    def on_options(req, resp):
15
        resp.status = falcon.HTTP_200
16
17
    ####################################################################################################################
18
    # PROCEDURES
19
    # Step 1: valid parameters
20
    # Step 2: build a space tree
21
    # Step 3: query all equipments in the space tree
22
    # Step 4: construct the report
23
    ####################################################################################################################
24
    @staticmethod
25
    def on_get(req, resp):
26
        print(req.params)
27
        space_id = req.params.get('spaceid')
28
29
        ################################################################################################################
30
        # Step 1: valid parameters
31
        ################################################################################################################
32
        if space_id is None:
33
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID')
34
        else:
35
            space_id = str.strip(space_id)
36
            if not space_id.isdigit() or int(space_id) <= 0:
37
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID')
38
            else:
39
                space_id = int(space_id)
40
41
        cnx = mysql.connector.connect(**config.myems_system_db)
42
        cursor = cnx.cursor(dictionary=True)
43
44
        cursor.execute(" SELECT name "
45
                       " FROM tbl_spaces "
46
                       " WHERE id = %s ", (space_id,))
47
        if cursor.fetchone() is None:
48
            if cursor:
49
                cursor.close()
50
            if cnx:
51
                cnx.disconnect()
52
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
53
                                   description='API.SPACE_NOT_FOUND')
54
55
        ################################################################################################################
56
        # Step 2: build a space tree
57
        ################################################################################################################
58
59
        query = (" SELECT id, name, parent_space_id "
60
                 " FROM tbl_spaces "
61
                 " ORDER BY id ")
62
        cursor.execute(query)
63
        rows_spaces = cursor.fetchall()
64
        node_dict = dict()
65
        if rows_spaces is not None and len(rows_spaces) > 0:
66
            for row in rows_spaces:
67
                parent_node = node_dict[row['parent_space_id']] if row['parent_space_id'] is not None else None
68
                node_dict[row['id']] = AnyNode(id=row['id'], parent=parent_node, name=row['name'])
69
70
        ################################################################################################################
71
        # Step 3: query all equipments in the space tree
72
        ################################################################################################################
73
        equipment_list = list()
74
        space_dict = dict()
75
76
        for node in LevelOrderIter(node_dict[space_id]):
77
            space_dict[node.id] = node.name
78
79
        cursor.execute(" SELECT e.id, e.name AS equipment_name, s.name AS space_name, "
80
                       "        cc.name AS cost_center_name, e.description "
81
                       " FROM tbl_spaces s, tbl_spaces_equipments se, tbl_equipments e, tbl_cost_centers cc "
82
                       " WHERE s.id IN ( " + ', '.join(map(str, space_dict.keys())) + ") "
83
                       "       AND se.space_id = s.id "
84
                       "       AND se.equipment_id = e.id "
85
                       "       AND e.cost_center_id = cc.id  ", )
86
        rows_equipments = cursor.fetchall()
87
        if rows_equipments is not None and len(rows_equipments) > 0:
88
            for row in rows_equipments:
89
                equipment_list.append({"id": row['id'],
90
                                       "equipment_name": row['equipment_name'],
91
                                       "space_name": row['space_name'],
92
                                       "cost_center_name": row['cost_center_name'],
93
                                       "description": row['description']})
94
95
        if cursor:
96
            cursor.close()
97
        if cnx:
98
            cnx.disconnect()
99
100
        ################################################################################################################
101
        # Step 4: construct the report
102
        ################################################################################################################
103
104
        resp.body = json.dumps(equipment_list)
105