Conditions | 31 |
Total Lines | 161 |
Code Lines | 119 |
Lines | 60 |
Ratio | 37.27 % |
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 core.tariff.TariffItem.on_put() 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 |
||
350 | @staticmethod |
||
351 | def on_put(req, resp, id_): |
||
352 | """Handles PUT requests""" |
||
353 | try: |
||
354 | raw_json = req.stream.read().decode('utf-8') |
||
355 | except Exception as ex: |
||
356 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) |
||
357 | |||
358 | if not id_.isdigit() or int(id_) <= 0: |
||
359 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
360 | description='API.INVALID_TARIFF_ID') |
||
361 | |||
362 | new_values = json.loads(raw_json) |
||
363 | |||
364 | if 'name' not in new_values['data'].keys() or \ |
||
365 | not isinstance(new_values['data']['name'], str) or \ |
||
366 | len(str.strip(new_values['data']['name'])) == 0: |
||
367 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
368 | description='API.INVALID_METER_NAME') |
||
369 | name = str.strip(new_values['data']['name']) |
||
370 | |||
371 | if 'energy_category' not in new_values['data'].keys() or \ |
||
372 | 'id' not in new_values['data']['energy_category'].keys() or \ |
||
373 | not isinstance(new_values['data']['energy_category']['id'], int) or \ |
||
374 | new_values['data']['energy_category']['id'] <= 0: |
||
375 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
376 | description='API.INVALID_ENERGY_CATEGORY_ID') |
||
377 | energy_category_id = new_values['data']['energy_category']['id'] |
||
378 | |||
379 | if 'tariff_type' not in new_values['data'].keys() \ |
||
380 | or str.strip(new_values['data']['tariff_type']) not in ('block', 'timeofuse'): |
||
381 | raise falcon.HTTPError(falcon.HTTP_400, |
||
382 | title='API.BAD_REQUEST', |
||
383 | description='API.INVALID_TARIFF_TYPE') |
||
384 | tariff_type = str.strip(new_values['data']['tariff_type']) |
||
385 | |||
386 | View Code Duplication | if new_values['data']['tariff_type'] == 'block': |
|
387 | if new_values['data']['block'] is None: |
||
388 | raise falcon.HTTPError(falcon.HTTP_400, |
||
389 | title='API.BAD_REQUEST', |
||
390 | description='API.INVALID_TARIFF_BLOCK_PRICING') |
||
391 | elif new_values['data']['tariff_type'] == 'timeofuse': |
||
392 | if new_values['data']['timeofuse'] is None: |
||
393 | raise falcon.HTTPError(falcon.HTTP_400, |
||
394 | title='API.BAD_REQUEST', |
||
395 | description='API.INVALID_TARIFF_TIME_OF_USE_PRICING') |
||
396 | |||
397 | if 'unit_of_price' not in new_values['data'].keys() or \ |
||
398 | not isinstance(new_values['data']['unit_of_price'], str) or \ |
||
399 | len(str.strip(new_values['data']['unit_of_price'])) == 0: |
||
400 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
401 | description='API.INVALID_UNIT_OF_PRICE') |
||
402 | unit_of_price = str.strip(new_values['data']['unit_of_price']) |
||
403 | |||
404 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
405 | if config.utc_offset[0] == '-': |
||
406 | timezone_offset = -timezone_offset |
||
407 | |||
408 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
409 | cursor = cnx.cursor() |
||
410 | |||
411 | # check if the tariff exist |
||
412 | query = (" SELECT name " |
||
413 | " FROM tbl_tariffs " |
||
414 | " WHERE id = %s ") |
||
415 | cursor.execute(query, (id_,)) |
||
416 | cursor.fetchone() |
||
417 | |||
418 | if cursor.rowcount != 1: |
||
419 | cursor.close() |
||
420 | cnx.disconnect() |
||
421 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
422 | description='API.TARIFF_NOT_FOUND') |
||
423 | |||
424 | cursor.execute(" SELECT name " |
||
425 | " FROM tbl_tariffs " |
||
426 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
427 | if cursor.fetchone() is not None: |
||
428 | cursor.close() |
||
429 | cnx.disconnect() |
||
430 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
431 | description='API.TARIFF_NAME_IS_ALREADY_IN_USE') |
||
432 | |||
433 | valid_from = datetime.strptime(new_values['data']['valid_from'], '%Y-%m-%dT%H:%M:%S') |
||
434 | valid_from = valid_from.replace(tzinfo=timezone.utc) |
||
435 | valid_from -= timedelta(minutes=timezone_offset) |
||
436 | valid_through = datetime.strptime(new_values['data']['valid_through'], '%Y-%m-%dT%H:%M:%S') |
||
437 | valid_through = valid_through.replace(tzinfo=timezone.utc) |
||
438 | valid_through -= timedelta(minutes=timezone_offset) |
||
439 | |||
440 | # update tariff itself |
||
441 | update_row = (" UPDATE tbl_tariffs " |
||
442 | " SET name = %s, energy_category_id = %s, tariff_type = %s, unit_of_price = %s, " |
||
443 | " valid_from_datetime_utc = %s , valid_through_datetime_utc = %s " |
||
444 | " WHERE id = %s ") |
||
445 | cursor.execute(update_row, (name, |
||
446 | energy_category_id, |
||
447 | tariff_type, |
||
448 | unit_of_price, |
||
449 | valid_from, |
||
450 | valid_through, |
||
451 | id_,)) |
||
452 | cnx.commit() |
||
453 | |||
454 | # update prices of the tariff |
||
455 | if tariff_type == 'block': |
||
456 | View Code Duplication | if 'block' not in new_values['data'].keys() or new_values['data']['block'] is None: |
|
457 | cursor.close() |
||
458 | cnx.disconnect() |
||
459 | raise falcon.HTTPError(falcon.HTTP_400, |
||
460 | title='API.BAD_REQUEST', |
||
461 | description='API.INVALID_TARIFF_BLOCK_PRICING') |
||
462 | else: |
||
463 | # remove all (possible) exist prices |
||
464 | cursor.execute(" DELETE FROM tbl_tariffs_blocks " |
||
465 | " WHERE tariff_id = %s ", |
||
466 | (id_,)) |
||
467 | |||
468 | cursor.execute(" DELETE FROM tbl_tariffs_timeofuses " |
||
469 | " WHERE tariff_id = %s ", |
||
470 | (id_,)) |
||
471 | cnx.commit() |
||
472 | |||
473 | for block in new_values['data']['block']: |
||
474 | cursor.execute(" INSERT INTO tbl_tariffs_blocks " |
||
475 | " (tariff_id, start_amount, end_amount, price) " |
||
476 | " VALUES (%s, %s, %s, %s) ", |
||
477 | (id_, block['start_amount'], block['end_amount'], block['price'])) |
||
478 | cnx.commit() |
||
479 | elif tariff_type == 'timeofuse': |
||
480 | View Code Duplication | if 'timeofuse' not in new_values['data'].keys() or new_values['data']['timeofuse'] is None: |
|
481 | cursor.close() |
||
482 | cnx.disconnect() |
||
483 | raise falcon.HTTPError(falcon.HTTP_400, |
||
484 | title='API.BAD_REQUEST', |
||
485 | description='API.INVALID_TARIFF_TIME_OF_USE_PRICING') |
||
486 | else: |
||
487 | # remove all (possible) exist prices |
||
488 | cursor.execute(" DELETE FROM tbl_tariffs_blocks " |
||
489 | " WHERE tariff_id = %s ", |
||
490 | (id_,)) |
||
491 | |||
492 | cursor.execute(" DELETE FROM tbl_tariffs_timeofuses " |
||
493 | " WHERE tariff_id = %s ", |
||
494 | (id_,)) |
||
495 | cnx.commit() |
||
496 | |||
497 | for timeofuse in new_values['data']['timeofuse']: |
||
498 | add_timeofuse = (" INSERT INTO tbl_tariffs_timeofuses " |
||
499 | " (tariff_id, start_time_of_day, end_time_of_day, peak_type, price) " |
||
500 | " VALUES (%s, %s, %s, %s, %s) ") |
||
501 | cursor.execute(add_timeofuse, (id_, |
||
502 | timeofuse['start_time_of_day'], |
||
503 | timeofuse['end_time_of_day'], |
||
504 | timeofuse['peak_type'], |
||
505 | timeofuse['price'])) |
||
506 | cnx.commit() |
||
507 | |||
508 | cursor.close() |
||
509 | cnx.disconnect() |
||
510 | resp.status = falcon.HTTP_200 |
||
511 | |||
513 |