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