Code Duplication    Length = 111-111 lines in 3 locations

myems-api/core/microgrid.py 1 location

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

myems-api/core/energystoragepowerstation.py 1 location

@@ 970-1080 (lines=111) @@
967
        resp.text = json.dumps(result)
968
969
970
class EnergyStoragePowerStationUserCollection:
971
    def __init__(self):
972
        """Initializes Class"""
973
        pass
974
975
    @staticmethod
976
    def on_options(req, resp, id_):
977
        _ = req
978
        resp.status = falcon.HTTP_200
979
        _ = id_
980
981
    @staticmethod
982
    def on_get(req, resp, id_):
983
        access_control(req)
984
        if not id_.isdigit() or int(id_) <= 0:
985
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
986
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
987
988
        cnx = mysql.connector.connect(**config.myems_system_db)
989
        cursor = cnx.cursor()
990
        cursor.execute(" SELECT name "
991
                       " FROM tbl_energy_storage_power_stations "
992
                       " WHERE id = %s ", (id_,))
993
        if cursor.fetchone() is None:
994
            cursor.close()
995
            cnx.close()
996
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
997
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
998
999
        query = (" SELECT u.id, u.name, u.uuid "
1000
                 " FROM tbl_energy_storage_power_stations m, tbl_energy_storage_power_stations_users mu, "
1001
                 + config.myems_user_db['database'] + ".tbl_users u "
1002
                 " WHERE mu.energy_storage_power_station_id = m.id AND u.id = mu.user_id AND m.id = %s "
1003
                 " ORDER BY u.id ")
1004
        cursor.execute(query, (id_,))
1005
        rows = cursor.fetchall()
1006
        result = list()
1007
        if rows is not None and len(rows) > 0:
1008
            for row in rows:
1009
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1010
                result.append(meta_result)
1011
1012
        cursor.close()
1013
        cnx.close()
1014
        resp.text = json.dumps(result)
1015
1016
    @staticmethod
1017
    @user_logger
1018
    def on_post(req, resp, id_):
1019
        """Handles POST requests"""
1020
        admin_control(req)
1021
        try:
1022
            raw_json = req.stream.read().decode('utf-8')
1023
        except Exception as ex:
1024
            print(str(ex))
1025
            raise falcon.HTTPError(status=falcon.HTTP_400,
1026
                                   title='API.BAD_REQUEST',
1027
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1028
1029
        if not id_.isdigit() or int(id_) <= 0:
1030
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1031
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
1032
1033
        new_values = json.loads(raw_json)
1034
        if 'user_id' not in new_values['data'].keys() or \
1035
                not isinstance(new_values['data']['user_id'], int) or \
1036
                new_values['data']['user_id'] <= 0:
1037
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1038
                                   description='API.INVALID_USER_ID')
1039
        user_id = new_values['data']['user_id']
1040
        cnx = mysql.connector.connect(**config.myems_system_db)
1041
        cursor = cnx.cursor()
1042
        cursor.execute(" SELECT name "
1043
                       " FROM tbl_energy_storage_power_stations "
1044
                       " WHERE id = %s ", (id_,))
1045
        if cursor.fetchone() is None:
1046
            cursor.close()
1047
            cnx.close()
1048
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1049
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
1050
1051
        cnx_user = mysql.connector.connect(**config.myems_user_db)
1052
        cursor_user = cnx_user.cursor()
1053
        cursor_user.execute(" SELECT name"
1054
                            " FROM tbl_users "
1055
                            " WHERE id = %s ", (user_id,))
1056
        if cursor_user.fetchone() is None:
1057
            cursor_user.close()
1058
            cnx_user.close()
1059
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1060
                                   description='API.USER_NOT_FOUND')
1061
        query = (" SELECT id "
1062
                 " FROM tbl_energy_storage_power_stations_users "
1063
                 " WHERE energy_storage_power_station_id = %s AND user_id = %s")
1064
        cursor.execute(query, (id_, user_id,))
1065
        if cursor.fetchone() is not None:
1066
            cursor.close()
1067
            cnx.close()
1068
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1069
                                   description='API.ENERGY_STORAGE_POWER_STATION_USER_RELATION_EXISTS')
1070
        add_row = (" INSERT INTO tbl_energy_storage_power_stations_users (energy_storage_power_station_id, user_id) "
1071
                   " VALUES (%s, %s) ")
1072
        cursor.execute(add_row, (id_, user_id,))
1073
        cnx.commit()
1074
        cursor.close()
1075
        cnx.close()
1076
        cursor_user.close()
1077
        cnx_user.close()
1078
1079
        resp.status = falcon.HTTP_201
1080
        resp.location = '/energystoragepowerstations/' + str(id_) + '/users/' + str(user_id)
1081
1082
1083
class EnergyStoragePowerStationUserItem:

myems-api/core/photovoltaicpowerstation.py 1 location

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