Conditions | 30 |
Total Lines | 180 |
Code Lines | 122 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
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:
If many parameters/temporary variables are present:
Complex classes like reports.meterrealtime.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 |
||
28 | @staticmethod |
||
29 | def on_get(req, resp): |
||
30 | print(req.params) |
||
31 | meter_id = req.params.get('meterid') |
||
32 | |||
33 | ################################################################################################################ |
||
34 | # Step 1: valid parameters |
||
35 | ################################################################################################################ |
||
36 | if meter_id is None: |
||
37 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID') |
||
38 | else: |
||
39 | meter_id = str.strip(meter_id) |
||
40 | if not meter_id.isdigit() or int(meter_id) <= 0: |
||
41 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID') |
||
42 | |||
43 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
44 | if config.utc_offset[0] == '-': |
||
45 | timezone_offset = -timezone_offset |
||
46 | |||
47 | reporting_end_datetime_utc = datetime.utcnow() |
||
48 | reporting_start_datetime_utc = reporting_end_datetime_utc - timedelta(minutes=60) |
||
49 | ################################################################################################################ |
||
50 | # Step 2: query the meter and energy category |
||
51 | ################################################################################################################ |
||
52 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
53 | cursor_system = cnx_system.cursor() |
||
54 | |||
55 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
||
56 | cursor_historical = cnx_historical.cursor() |
||
57 | |||
58 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
||
59 | " ec.name, ec.unit_of_measure " |
||
60 | " FROM tbl_meters m, tbl_energy_categories ec " |
||
61 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,)) |
||
62 | row_meter = cursor_system.fetchone() |
||
63 | if row_meter is None: |
||
64 | if cursor_system: |
||
65 | cursor_system.close() |
||
66 | if cnx_system: |
||
67 | cnx_system.disconnect() |
||
68 | |||
69 | if cursor_historical: |
||
70 | cursor_historical.close() |
||
71 | if cnx_historical: |
||
72 | cnx_historical.disconnect() |
||
73 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND') |
||
74 | |||
75 | meter = dict() |
||
76 | meter['id'] = row_meter[0] |
||
77 | meter['name'] = row_meter[1] |
||
78 | meter['cost_center_id'] = row_meter[2] |
||
79 | meter['energy_category_id'] = row_meter[3] |
||
80 | meter['energy_category_name'] = row_meter[4] |
||
81 | meter['unit_of_measure'] = row_meter[5] |
||
82 | |||
83 | ################################################################################################################ |
||
84 | # Step 3: query associated points |
||
85 | ################################################################################################################ |
||
86 | point_list = list() |
||
87 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
||
88 | " FROM tbl_meters m, tbl_meters_points mp, tbl_points p " |
||
89 | " WHERE m.id = %s AND m.id = mp.meter_id AND mp.point_id = p.id " |
||
90 | " ORDER BY p.id ", (meter['id'],)) |
||
91 | rows_points = cursor_system.fetchall() |
||
92 | if rows_points is not None and len(rows_points) > 0: |
||
93 | for row in rows_points: |
||
94 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
95 | |||
96 | ################################################################################################################ |
||
97 | # Step 7: query associated points data |
||
98 | ################################################################################################################ |
||
99 | energy_value_data = dict() |
||
100 | energy_value_data['name'] = None |
||
101 | energy_value_data['timestamps'] = list() |
||
102 | energy_value_data['values'] = list() |
||
103 | |||
104 | parameters_data = dict() |
||
105 | parameters_data['names'] = list() |
||
106 | parameters_data['timestamps'] = list() |
||
107 | parameters_data['values'] = list() |
||
108 | |||
109 | for point in point_list: |
||
110 | point_values = [] |
||
111 | point_timestamps = [] |
||
112 | if point['object_type'] == 'ANALOG_VALUE': |
||
113 | |||
114 | query = (" SELECT utc_date_time, actual_value " |
||
115 | " FROM tbl_analog_value " |
||
116 | " WHERE point_id = %s " |
||
117 | " AND utc_date_time BETWEEN %s AND %s " |
||
118 | " ORDER BY utc_date_time ") |
||
119 | cursor_historical.execute(query, (point['id'], |
||
120 | reporting_start_datetime_utc, |
||
121 | reporting_end_datetime_utc)) |
||
122 | rows = cursor_historical.fetchall() |
||
123 | |||
124 | if rows is not None and len(rows) > 0: |
||
125 | for row in rows: |
||
126 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
127 | timedelta(minutes=timezone_offset) |
||
128 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
129 | point_timestamps.append(current_datetime) |
||
130 | point_values.append(row[1]) |
||
131 | |||
132 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
||
133 | parameters_data['timestamps'].append(point_timestamps) |
||
134 | parameters_data['values'].append(point_values) |
||
135 | elif point['object_type'] == 'ENERGY_VALUE': |
||
136 | energy_value_data['name'] = point['name'] |
||
137 | query = (" SELECT utc_date_time, actual_value " |
||
138 | " FROM tbl_energy_value " |
||
139 | " WHERE point_id = %s " |
||
140 | " AND utc_date_time BETWEEN %s AND %s " |
||
141 | " ORDER BY utc_date_time ") |
||
142 | cursor_historical.execute(query, (point['id'], |
||
143 | reporting_start_datetime_utc, |
||
144 | reporting_end_datetime_utc)) |
||
145 | rows = cursor_historical.fetchall() |
||
146 | |||
147 | if rows is not None and len(rows) > 0: |
||
148 | |||
149 | for row in rows: |
||
150 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
151 | timedelta(minutes=timezone_offset) |
||
152 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
153 | energy_value_data['timestamps'].append(current_datetime) |
||
154 | energy_value_data['values'].append(row[1]) |
||
155 | |||
156 | elif point['object_type'] == 'DIGITAL_VALUE': |
||
157 | query = (" SELECT utc_date_time, actual_value " |
||
158 | " FROM tbl_digital_value " |
||
159 | " WHERE point_id = %s " |
||
160 | " AND utc_date_time BETWEEN %s AND %s ") |
||
161 | cursor_historical.execute(query, (point['id'], |
||
162 | reporting_start_datetime_utc, |
||
163 | reporting_end_datetime_utc)) |
||
164 | rows = cursor_historical.fetchall() |
||
165 | |||
166 | if rows is not None and len(rows) > 0: |
||
167 | for row in rows: |
||
168 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
169 | timedelta(minutes=timezone_offset) |
||
170 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
171 | point_timestamps.append(current_datetime) |
||
172 | point_values.append(row[1]) |
||
173 | |||
174 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
||
175 | parameters_data['timestamps'].append(point_timestamps) |
||
176 | parameters_data['values'].append(point_values) |
||
177 | |||
178 | ################################################################################################################ |
||
179 | # Step 6: construct the report |
||
180 | ################################################################################################################ |
||
181 | if cursor_system: |
||
182 | cursor_system.close() |
||
183 | if cnx_system: |
||
184 | cnx_system.disconnect() |
||
185 | |||
186 | if cursor_historical: |
||
187 | cursor_historical.close() |
||
188 | if cnx_historical: |
||
189 | cnx_historical.disconnect() |
||
190 | |||
191 | result = { |
||
192 | "meter": { |
||
193 | "cost_center_id": meter['cost_center_id'], |
||
194 | "energy_category_id": meter['energy_category_id'], |
||
195 | "energy_category_name": meter['energy_category_name'], |
||
196 | "unit_of_measure": meter['unit_of_measure'], |
||
197 | }, |
||
198 | "energy_value": energy_value_data, |
||
199 | "parameters": { |
||
200 | "names": parameters_data['names'], |
||
201 | "timestamps": parameters_data['timestamps'], |
||
202 | "values": parameters_data['values'] |
||
203 | }, |
||
204 | |||
205 | } |
||
206 | |||
207 | resp.body = json.dumps(result) |
||
208 |