Code Duplication    Length = 111-111 lines in 3 locations

myems-api/core/energystoragepowerstation.py 1 location

@@ 1021-1131 (lines=111) @@
1018
        resp.text = json.dumps(result)
1019
1020
1021
class EnergyStoragePowerStationUserCollection:
1022
    def __init__(self):
1023
        pass
1024
1025
    @staticmethod
1026
    def on_options(req, resp, id_):
1027
        _ = req
1028
        resp.status = falcon.HTTP_200
1029
        _ = id_
1030
1031
    @staticmethod
1032
    def on_get(req, resp, id_):
1033
        access_control(req)
1034
        if not id_.isdigit() or int(id_) <= 0:
1035
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1036
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1037
1038
        cnx = mysql.connector.connect(**config.myems_system_db)
1039
        cursor = cnx.cursor()
1040
        cursor.execute(" SELECT name "
1041
                       " FROM tbl_energy_storage_power_stations "
1042
                       " WHERE id = %s ", (id_,))
1043
        if cursor.fetchone() is None:
1044
            cursor.close()
1045
            cnx.close()
1046
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1047
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1048
1049
        query = (" SELECT u.id, u.name, u.uuid "
1050
                 " FROM tbl_energy_storage_power_stations m, tbl_energy_storage_power_stations_users mu, "
1051
                 + config.myems_user_db['database'] + ".tbl_users u "
1052
                 " WHERE mu.energy_storage_power_station_id = m.id AND u.id = mu.user_id AND m.id = %s "
1053
                 " ORDER BY u.id ")
1054
        cursor.execute(query, (id_,))
1055
        rows = cursor.fetchall()
1056
        result = list()
1057
        if rows is not None and len(rows) > 0:
1058
            for row in rows:
1059
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1060
                result.append(meta_result)
1061
1062
        cursor.close()
1063
        cnx.close()
1064
        resp.text = json.dumps(result)
1065
1066
    @staticmethod
1067
    @user_logger
1068
    def on_post(req, resp, id_):
1069
        """Handles POST requests"""
1070
        admin_control(req)
1071
        try:
1072
            raw_json = req.stream.read().decode('utf-8')
1073
        except Exception as ex:
1074
            print(str(ex))
1075
            raise falcon.HTTPError(status=falcon.HTTP_400,
1076
                                   title='API.BAD_REQUEST',
1077
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1078
1079
        if not id_.isdigit() or int(id_) <= 0:
1080
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1081
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1082
1083
        new_values = json.loads(raw_json)
1084
        if 'user_id' not in new_values['data'].keys() or \
1085
                not isinstance(new_values['data']['user_id'], int) or \
1086
                new_values['data']['user_id'] <= 0:
1087
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1088
                                   description='API.INVALID_USER_ID')
1089
        user_id = new_values['data']['user_id']
1090
        cnx = mysql.connector.connect(**config.myems_system_db)
1091
        cursor = cnx.cursor()
1092
        cursor.execute(" SELECT name "
1093
                       " FROM tbl_energy_storage_power_stations "
1094
                       " WHERE id = %s ", (id_,))
1095
        if cursor.fetchone() is None:
1096
            cursor.close()
1097
            cnx.close()
1098
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1099
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1100
1101
        cnx_user = mysql.connector.connect(**config.myems_user_db)
1102
        cursor_user = cnx_user.cursor()
1103
        cursor_user.execute(" SELECT name"
1104
                            " FROM tbl_users "
1105
                            " WHERE id = %s ", (user_id,))
1106
        if cursor_user.fetchone() is None:
1107
            cursor_user.close()
1108
            cnx_user.close()
1109
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1110
                                   description='API.USER_NOT_FOUND')
1111
        query = (" SELECT id "
1112
                 " FROM tbl_energy_storage_power_stations_users "
1113
                 " WHERE energy_storage_power_station_id = %s AND user_id = %s")
1114
        cursor.execute(query, (id_, user_id,))
1115
        if cursor.fetchone() is not None:
1116
            cursor.close()
1117
            cnx.close()
1118
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1119
                                   description='API.ENERGY_STORAGE_POWER_STATION_USER_RELATION_EXISTS')
1120
        add_row = (" INSERT INTO tbl_energy_storage_power_stations_users (energy_storage_power_station_id, user_id) "
1121
                   " VALUES (%s, %s) ")
1122
        cursor.execute(add_row, (id_, user_id,))
1123
        cnx.commit()
1124
        cursor.close()
1125
        cnx.close()
1126
        cursor_user.close()
1127
        cnx_user.close()
1128
1129
        resp.status = falcon.HTTP_201
1130
        resp.location = '/energystoragepowerstations/' + str(id_) + '/users/' + str(user_id)
1131
1132
1133
class EnergyStoragePowerStationUserItem:
1134
    def __init__(self):

myems-api/core/microgrid.py 1 location

@@ 5056-5166 (lines=111) @@
5053
        resp.status = falcon.HTTP_204
5054
5055
5056
class MicrogridUserCollection:
5057
    def __init__(self):
5058
        pass
5059
5060
    @staticmethod
5061
    def on_options(req, resp, id_):
5062
        _ = req
5063
        resp.status = falcon.HTTP_200
5064
        _ = id_
5065
5066
    @staticmethod
5067
    def on_get(req, resp, id_):
5068
        access_control(req)
5069
        if not id_.isdigit() or int(id_) <= 0:
5070
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5071
                                   description='API.INVALID_MICROGRID_ID')
5072
5073
        cnx = mysql.connector.connect(**config.myems_system_db)
5074
        cursor = cnx.cursor()
5075
        cursor.execute(" SELECT name "
5076
                       " FROM tbl_microgrids "
5077
                       " WHERE id = %s ", (id_,))
5078
        if cursor.fetchone() is None:
5079
            cursor.close()
5080
            cnx.close()
5081
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5082
                                   description='API.MICROGRID_NOT_FOUND')
5083
5084
        query = (" SELECT u.id, u.name, u.uuid "
5085
                 " FROM tbl_microgrids m, tbl_microgrids_users mu, "
5086
                 + config.myems_user_db['database'] + ".tbl_users u "
5087
                 " WHERE mu.microgrid_id = m.id AND u.id = mu.user_id AND m.id = %s "
5088
                 " ORDER BY u.id ")
5089
        cursor.execute(query, (id_,))
5090
        rows = cursor.fetchall()
5091
        result = list()
5092
        if rows is not None and len(rows) > 0:
5093
            for row in rows:
5094
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
5095
                result.append(meta_result)
5096
5097
        cursor.close()
5098
        cnx.close()
5099
        resp.text = json.dumps(result)
5100
5101
    @staticmethod
5102
    @user_logger
5103
    def on_post(req, resp, id_):
5104
        """Handles POST requests"""
5105
        admin_control(req)
5106
        try:
5107
            raw_json = req.stream.read().decode('utf-8')
5108
        except Exception as ex:
5109
            print(str(ex))
5110
            raise falcon.HTTPError(status=falcon.HTTP_400,
5111
                                   title='API.BAD_REQUEST',
5112
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5113
5114
        if not id_.isdigit() or int(id_) <= 0:
5115
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5116
                                   description='API.INVALID_MICROGRID_ID')
5117
5118
        new_values = json.loads(raw_json)
5119
        if 'user_id' not in new_values['data'].keys() or \
5120
                not isinstance(new_values['data']['user_id'], int) or \
5121
                new_values['data']['user_id'] <= 0:
5122
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5123
                                   description='API.INVALID_USER_ID')
5124
        user_id = new_values['data']['user_id']
5125
        cnx = mysql.connector.connect(**config.myems_system_db)
5126
        cursor = cnx.cursor()
5127
        cursor.execute(" SELECT name "
5128
                       " from tbl_microgrids "
5129
                       " WHERE id = %s ", (id_,))
5130
        if cursor.fetchone() is None:
5131
            cursor.close()
5132
            cnx.close()
5133
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5134
                                   description='API.MICROGRID_NOT_FOUND')
5135
5136
        cnx_user = mysql.connector.connect(**config.myems_user_db)
5137
        cursor_user = cnx_user.cursor()
5138
        cursor_user.execute(" SELECT name"
5139
                            " FROM tbl_users "
5140
                            " WHERE id = %s ", (user_id,))
5141
        if cursor_user.fetchone() is None:
5142
            cursor_user.close()
5143
            cnx_user.close()
5144
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5145
                                   description='API.USER_NOT_FOUND')
5146
        query = (" SELECT id "
5147
                 " FROM tbl_microgrids_users "
5148
                 " WHERE microgrid_id = %s AND user_id = %s")
5149
        cursor.execute(query, (id_, user_id,))
5150
        if cursor.fetchone() is not None:
5151
            cursor.close()
5152
            cnx.close()
5153
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5154
                                   description='API.MICROGRID_USER_RELATION_EXISTS')
5155
        add_row = (" INSERT INTO tbl_microgrids_users (microgrid_id, user_id) "
5156
                   " VALUES (%s, %s) ")
5157
        cursor.execute(add_row, (id_, user_id,))
5158
        cnx.commit()
5159
        cursor.close()
5160
        cnx.close()
5161
        cursor_user.close()
5162
        cnx_user.close()
5163
5164
        resp.status = falcon.HTTP_201
5165
        resp.location = '/microgrids/' + str(id_) + '/users/' + str(user_id)
5166
5167
5168
class MicrogridUserItem:
5169
    def __init__(self):

myems-api/core/photovoltaicpowerstation.py 1 location

@@ 4883-4993 (lines=111) @@
4880
        resp.status = falcon.HTTP_200
4881
4882
4883
class PhotovoltaicPowerStationUserCollection:
4884
    def __init__(self):
4885
        pass
4886
4887
    @staticmethod
4888
    def on_options(req, resp, id_):
4889
        _ = req
4890
        resp.status = falcon.HTTP_200
4891
        _ = id_
4892
4893
    @staticmethod
4894
    def on_get(req, resp, id_):
4895
        access_control(req)
4896
        if not id_.isdigit() or int(id_) <= 0:
4897
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4898
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
4899
4900
        cnx = mysql.connector.connect(**config.myems_system_db)
4901
        cursor = cnx.cursor()
4902
        cursor.execute(" SELECT name "
4903
                       " FROM tbl_photovoltaic_power_stations "
4904
                       " WHERE id = %s ", (id_,))
4905
        if cursor.fetchone() is None:
4906
            cursor.close()
4907
            cnx.close()
4908
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4909
                                   description='API.PHOTOVOLTAIC_POWER_STATION_NOT_FOUND')
4910
4911
        query = (" SELECT u.id, u.name, u.uuid "
4912
                 " FROM tbl_photovoltaic_power_stations m, tbl_photovoltaic_power_stations_users mu, "
4913
                 + config.myems_user_db['database'] + ".tbl_users u "
4914
                 " WHERE mu.photovoltaic_power_station_id = m.id AND u.id = mu.user_id AND m.id = %s "
4915
                 " ORDER BY u.id ")
4916
        cursor.execute(query, (id_,))
4917
        rows = cursor.fetchall()
4918
        result = list()
4919
        if rows is not None and len(rows) > 0:
4920
            for row in rows:
4921
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
4922
                result.append(meta_result)
4923
4924
        cursor.close()
4925
        cnx.close()
4926
        resp.text = json.dumps(result)
4927
4928
    @staticmethod
4929
    @user_logger
4930
    def on_post(req, resp, id_):
4931
        """Handles POST requests"""
4932
        admin_control(req)
4933
        try:
4934
            raw_json = req.stream.read().decode('utf-8')
4935
        except Exception as ex:
4936
            print(str(ex))
4937
            raise falcon.HTTPError(status=falcon.HTTP_400,
4938
                                   title='API.BAD_REQUEST',
4939
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4940
4941
        if not id_.isdigit() or int(id_) <= 0:
4942
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4943
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
4944
4945
        new_values = json.loads(raw_json)
4946
        if 'user_id' not in new_values['data'].keys() or \
4947
                not isinstance(new_values['data']['user_id'], int) or \
4948
                new_values['data']['user_id'] <= 0:
4949
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4950
                                   description='API.INVALID_USER_ID')
4951
        user_id = new_values['data']['user_id']
4952
        cnx = mysql.connector.connect(**config.myems_system_db)
4953
        cursor = cnx.cursor()
4954
        cursor.execute(" SELECT name "
4955
                       " FROM tbl_photovoltaic_power_stations "
4956
                       " WHERE id = %s ", (id_,))
4957
        if cursor.fetchone() is None:
4958
            cursor.close()
4959
            cnx.close()
4960
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4961
                                   description='API.PHOTOVOLTAIC_POWER_STATION_NOT_FOUND')
4962
4963
        cnx_user = mysql.connector.connect(**config.myems_user_db)
4964
        cursor_user = cnx_user.cursor()
4965
        cursor_user.execute(" SELECT name"
4966
                            " FROM tbl_users "
4967
                            " WHERE id = %s ", (user_id,))
4968
        if cursor_user.fetchone() is None:
4969
            cursor_user.close()
4970
            cnx_user.close()
4971
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4972
                                   description='API.USER_NOT_FOUND')
4973
        query = (" SELECT id "
4974
                 " FROM tbl_photovoltaic_power_stations_users "
4975
                 " WHERE photovoltaic_power_station_id = %s AND user_id = %s")
4976
        cursor.execute(query, (id_, user_id,))
4977
        if cursor.fetchone() is not None:
4978
            cursor.close()
4979
            cnx.close()
4980
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4981
                                   description='API.PHOTOVOLTAIC_POWER_STATION_USER_RELATION_EXISTS')
4982
        add_row = (" INSERT INTO tbl_photovoltaic_power_stations_users (photovoltaic_power_station_id, user_id) "
4983
                   " VALUES (%s, %s) ")
4984
        cursor.execute(add_row, (id_, user_id,))
4985
        cnx.commit()
4986
        cursor.close()
4987
        cnx.close()
4988
        cursor_user.close()
4989
        cnx_user.close()
4990
4991
        resp.status = falcon.HTTP_201
4992
        resp.location = '/photovoltaicpowerstations/' + str(id_) + '/users/' + str(user_id)
4993
4994
4995
class PhotovoltaicPowerStationUserItem:
4996
    def __init__(self):