Conditions | 52 |
Total Lines | 346 |
Code Lines | 248 |
Lines | 346 |
Ratio | 100 % |
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.offlinemetercost.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 |
||
30 | @staticmethod |
||
31 | def on_get(req, resp): |
||
32 | print(req.params) |
||
33 | offline_meter_id = req.params.get('offlinemeterid') |
||
34 | period_type = req.params.get('periodtype') |
||
35 | base_period_start_datetime = req.params.get('baseperiodstartdatetime') |
||
36 | base_period_end_datetime = req.params.get('baseperiodenddatetime') |
||
37 | reporting_period_start_datetime = req.params.get('reportingperiodstartdatetime') |
||
38 | reporting_period_end_datetime = req.params.get('reportingperiodenddatetime') |
||
39 | |||
40 | ################################################################################################################ |
||
41 | # Step 1: valid parameters |
||
42 | ################################################################################################################ |
||
43 | if offline_meter_id is None: |
||
44 | raise falcon.HTTPError(falcon.HTTP_400, |
||
45 | title='API.BAD_REQUEST', |
||
46 | description='API.INVALID_OFFLINE_METER_ID') |
||
47 | else: |
||
48 | offline_meter_id = str.strip(offline_meter_id) |
||
49 | if not offline_meter_id.isdigit() or int(offline_meter_id) <= 0: |
||
50 | raise falcon.HTTPError(falcon.HTTP_400, |
||
51 | title='API.BAD_REQUEST', |
||
52 | description='API.INVALID_OFFLINE_METER_ID') |
||
53 | |||
54 | if period_type is None: |
||
55 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
56 | else: |
||
57 | period_type = str.strip(period_type) |
||
58 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
||
59 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
60 | |||
61 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
62 | if config.utc_offset[0] == '-': |
||
63 | timezone_offset = -timezone_offset |
||
64 | |||
65 | base_start_datetime_utc = None |
||
66 | if base_period_end_datetime is not None and len(str.strip(base_period_end_datetime)) > 0: |
||
67 | base_period_start_datetime = str.strip(base_period_start_datetime) |
||
68 | try: |
||
69 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime, '%Y-%m-%dT%H:%M:%S') |
||
70 | except ValueError: |
||
71 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
72 | description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME") |
||
73 | base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
74 | timedelta(minutes=timezone_offset) |
||
75 | |||
76 | base_end_datetime_utc = None |
||
77 | if base_period_end_datetime is not None and len(str.strip(base_period_end_datetime)) > 0: |
||
78 | base_period_end_datetime = str.strip(base_period_end_datetime) |
||
79 | try: |
||
80 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime, '%Y-%m-%dT%H:%M:%S') |
||
81 | except ValueError: |
||
82 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
83 | description="API.INVALID_BASE_PERIOD_ENDS_DATETIME") |
||
84 | base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
85 | timedelta(minutes=timezone_offset) |
||
86 | |||
87 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
||
88 | base_start_datetime_utc >= base_end_datetime_utc: |
||
89 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
90 | description='API.INVALID_BASE_PERIOD_ENDS_DATETIME') |
||
91 | |||
92 | if reporting_period_start_datetime is None: |
||
93 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
94 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
||
95 | else: |
||
96 | reporting_period_start_datetime = str.strip(reporting_period_start_datetime) |
||
97 | try: |
||
98 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime, '%Y-%m-%dT%H:%M:%S') |
||
99 | except ValueError: |
||
100 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
101 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
||
102 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
103 | timedelta(minutes=timezone_offset) |
||
104 | |||
105 | if reporting_period_end_datetime is None: |
||
106 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
107 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
||
108 | else: |
||
109 | reporting_period_end_datetime = str.strip(reporting_period_end_datetime) |
||
110 | try: |
||
111 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime, '%Y-%m-%dT%H:%M:%S') |
||
112 | except ValueError: |
||
113 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
114 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
||
115 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
116 | timedelta(minutes=timezone_offset) |
||
117 | |||
118 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
||
119 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
120 | description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME') |
||
121 | |||
122 | ################################################################################################################ |
||
123 | # Step 2: query the offline meter and energy category |
||
124 | ################################################################################################################ |
||
125 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
126 | cursor_system = cnx_system.cursor() |
||
127 | |||
128 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
||
129 | cursor_energy = cnx_energy.cursor() |
||
130 | |||
131 | cnx_billing = mysql.connector.connect(**config.myems_billing_db) |
||
132 | cursor_billing = cnx_billing.cursor() |
||
133 | |||
134 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
||
135 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
136 | " FROM tbl_offline_meters m, tbl_energy_categories ec " |
||
137 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (offline_meter_id,)) |
||
138 | row_offline_meter = cursor_system.fetchone() |
||
139 | if row_offline_meter is None: |
||
140 | if cursor_system: |
||
141 | cursor_system.close() |
||
142 | if cnx_system: |
||
143 | cnx_system.disconnect() |
||
144 | |||
145 | if cursor_energy: |
||
146 | cursor_energy.close() |
||
147 | if cnx_energy: |
||
148 | cnx_energy.disconnect() |
||
149 | |||
150 | if cursor_billing: |
||
151 | cursor_billing.close() |
||
152 | if cnx_billing: |
||
153 | cnx_billing.disconnect() |
||
154 | |||
155 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.OFFLINE_METER_NOT_FOUND') |
||
156 | |||
157 | offline_meter = dict() |
||
158 | offline_meter['id'] = row_offline_meter[0] |
||
159 | offline_meter['name'] = row_offline_meter[1] |
||
160 | offline_meter['cost_center_id'] = row_offline_meter[2] |
||
161 | offline_meter['energy_category_id'] = row_offline_meter[3] |
||
162 | offline_meter['energy_category_name'] = row_offline_meter[4] |
||
163 | offline_meter['unit_of_measure'] = config.currency_unit |
||
164 | offline_meter['kgce'] = row_offline_meter[6] |
||
165 | offline_meter['kgco2e'] = row_offline_meter[7] |
||
166 | |||
167 | ################################################################################################################ |
||
168 | # Step 3: query base period energy consumption |
||
169 | ################################################################################################################ |
||
170 | query = (" SELECT start_datetime_utc, actual_value " |
||
171 | " FROM tbl_offline_meter_hourly " |
||
172 | " WHERE offline_meter_id = %s " |
||
173 | " AND start_datetime_utc >= %s " |
||
174 | " AND start_datetime_utc < %s " |
||
175 | " ORDER BY start_datetime_utc ") |
||
176 | cursor_energy.execute(query, (offline_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
177 | rows_offline_meter_hourly = cursor_energy.fetchall() |
||
178 | |||
179 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
||
180 | base_start_datetime_utc, |
||
181 | base_end_datetime_utc, |
||
182 | period_type) |
||
183 | base = dict() |
||
184 | base['timestamps'] = list() |
||
185 | base['values'] = list() |
||
186 | base['total_in_category'] = Decimal(0.0) |
||
187 | base['total_in_kgce'] = Decimal(0.0) |
||
188 | base['total_in_kgco2e'] = Decimal(0.0) |
||
189 | |||
190 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
||
191 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
192 | timedelta(minutes=timezone_offset) |
||
193 | if period_type == 'hourly': |
||
194 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
195 | elif period_type == 'daily': |
||
196 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
197 | elif period_type == 'monthly': |
||
198 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
199 | elif period_type == 'yearly': |
||
200 | current_datetime = current_datetime_local.strftime('%Y') |
||
201 | |||
202 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
||
203 | else row_offline_meter_periodically[1] |
||
204 | base['timestamps'].append(current_datetime) |
||
205 | base['total_in_kgce'] += actual_value * offline_meter['kgce'] |
||
206 | base['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
||
207 | |||
208 | ################################################################################################################ |
||
209 | # Step 4: query base period energy cost |
||
210 | ################################################################################################################ |
||
211 | query = (" SELECT start_datetime_utc, actual_value " |
||
212 | " FROM tbl_offline_meter_hourly " |
||
213 | " WHERE offline_meter_id = %s " |
||
214 | " AND start_datetime_utc >= %s " |
||
215 | " AND start_datetime_utc < %s " |
||
216 | " ORDER BY start_datetime_utc ") |
||
217 | cursor_billing.execute(query, (offline_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
218 | rows_offline_meter_hourly = cursor_billing.fetchall() |
||
219 | |||
220 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
||
221 | base_start_datetime_utc, |
||
222 | base_end_datetime_utc, |
||
223 | period_type) |
||
224 | |||
225 | base['values'] = list() |
||
226 | base['total_in_category'] = Decimal(0.0) |
||
227 | |||
228 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
||
229 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
||
230 | else row_offline_meter_periodically[1] |
||
231 | base['values'].append(actual_value) |
||
232 | base['total_in_category'] += actual_value |
||
233 | |||
234 | ################################################################################################################ |
||
235 | # Step 5: query reporting period energy consumption |
||
236 | ################################################################################################################ |
||
237 | query = (" SELECT start_datetime_utc, actual_value " |
||
238 | " FROM tbl_offline_meter_hourly " |
||
239 | " WHERE offline_meter_id = %s " |
||
240 | " AND start_datetime_utc >= %s " |
||
241 | " AND start_datetime_utc < %s " |
||
242 | " ORDER BY start_datetime_utc ") |
||
243 | cursor_energy.execute(query, (offline_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
244 | rows_offline_meter_hourly = cursor_energy.fetchall() |
||
245 | |||
246 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
||
247 | reporting_start_datetime_utc, |
||
248 | reporting_end_datetime_utc, |
||
249 | period_type) |
||
250 | reporting = dict() |
||
251 | reporting['timestamps'] = list() |
||
252 | reporting['values'] = list() |
||
253 | reporting['total_in_category'] = Decimal(0.0) |
||
254 | reporting['total_in_kgce'] = Decimal(0.0) |
||
255 | reporting['total_in_kgco2e'] = Decimal(0.0) |
||
256 | |||
257 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
||
258 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
259 | timedelta(minutes=timezone_offset) |
||
260 | if period_type == 'hourly': |
||
261 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
262 | elif period_type == 'daily': |
||
263 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
264 | elif period_type == 'monthly': |
||
265 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
266 | elif period_type == 'yearly': |
||
267 | current_datetime = current_datetime_local.strftime('%Y') |
||
268 | |||
269 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
||
270 | else row_offline_meter_periodically[1] |
||
271 | |||
272 | reporting['timestamps'].append(current_datetime) |
||
273 | reporting['total_in_kgce'] += actual_value * offline_meter['kgce'] |
||
274 | reporting['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
||
275 | |||
276 | ################################################################################################################ |
||
277 | # Step 6: query reporting period energy cost |
||
278 | ################################################################################################################ |
||
279 | query = (" SELECT start_datetime_utc, actual_value " |
||
280 | " FROM tbl_offline_meter_hourly " |
||
281 | " WHERE offline_meter_id = %s " |
||
282 | " AND start_datetime_utc >= %s " |
||
283 | " AND start_datetime_utc < %s " |
||
284 | " ORDER BY start_datetime_utc ") |
||
285 | cursor_billing.execute(query, (offline_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
286 | rows_offline_meter_hourly = cursor_billing.fetchall() |
||
287 | |||
288 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
||
289 | reporting_start_datetime_utc, |
||
290 | reporting_end_datetime_utc, |
||
291 | period_type) |
||
292 | |||
293 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
||
294 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
||
295 | else row_offline_meter_periodically[1] |
||
296 | |||
297 | reporting['values'].append(actual_value) |
||
298 | reporting['total_in_category'] += actual_value |
||
299 | |||
300 | ################################################################################################################ |
||
301 | # Step 7: query tariff data |
||
302 | ################################################################################################################ |
||
303 | parameters_data = dict() |
||
304 | parameters_data['names'] = list() |
||
305 | parameters_data['timestamps'] = list() |
||
306 | parameters_data['values'] = list() |
||
307 | |||
308 | tariff_dict = utilities.get_energy_category_tariffs(offline_meter['cost_center_id'], |
||
309 | offline_meter['energy_category_id'], |
||
310 | reporting_start_datetime_utc, |
||
311 | reporting_end_datetime_utc) |
||
312 | tariff_timestamp_list = list() |
||
313 | tariff_value_list = list() |
||
314 | for k, v in tariff_dict.items(): |
||
315 | # convert k from utc to local |
||
316 | k = k + timedelta(minutes=timezone_offset) |
||
317 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
||
318 | tariff_value_list.append(v) |
||
319 | |||
320 | parameters_data['names'].append('TARIFF-' + offline_meter['energy_category_name']) |
||
321 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
322 | parameters_data['values'].append(tariff_value_list) |
||
323 | |||
324 | ################################################################################################################ |
||
325 | # Step 8: construct the report |
||
326 | ################################################################################################################ |
||
327 | if cursor_system: |
||
328 | cursor_system.close() |
||
329 | if cnx_system: |
||
330 | cnx_system.disconnect() |
||
331 | |||
332 | if cursor_energy: |
||
333 | cursor_energy.close() |
||
334 | if cnx_energy: |
||
335 | cnx_energy.disconnect() |
||
336 | |||
337 | if cursor_billing: |
||
338 | cursor_billing.close() |
||
339 | if cnx_billing: |
||
340 | cnx_billing.disconnect() |
||
341 | |||
342 | result = { |
||
343 | "offline_meter": { |
||
344 | "cost_center_id": offline_meter['cost_center_id'], |
||
345 | "energy_category_id": offline_meter['energy_category_id'], |
||
346 | "energy_category_name": offline_meter['energy_category_name'], |
||
347 | "unit_of_measure": config.currency_unit, |
||
348 | "kgce": offline_meter['kgce'], |
||
349 | "kgco2e": offline_meter['kgco2e'], |
||
350 | }, |
||
351 | "base_period": { |
||
352 | "total_in_category": base['total_in_category'], |
||
353 | "total_in_kgce": base['total_in_kgce'], |
||
354 | "total_in_kgco2e": base['total_in_kgco2e'], |
||
355 | "timestamps": base['timestamps'], |
||
356 | "values": base['values'], |
||
357 | }, |
||
358 | "reporting_period": { |
||
359 | "increment_rate": |
||
360 | (reporting['total_in_category']-base['total_in_category'])/base['total_in_category'] |
||
361 | if base['total_in_category'] > 0 else None, |
||
362 | "total_in_category": reporting['total_in_category'], |
||
363 | "total_in_kgce": reporting['total_in_kgce'], |
||
364 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
||
365 | "timestamps": reporting['timestamps'], |
||
366 | "values": reporting['values'], |
||
367 | }, |
||
368 | "parameters": { |
||
369 | "names": parameters_data['names'], |
||
370 | "timestamps": parameters_data['timestamps'], |
||
371 | "values": parameters_data['values'] |
||
372 | }, |
||
373 | } |
||
374 | |||
375 | resp.body = json.dumps(result) |
||
376 |