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