Code Duplication    Length = 108-108 lines in 4 locations

myems-api/core/hybridpowerstation.py 1 location

@@ 4954-5061 (lines=108) @@
4951
        resp.status = falcon.HTTP_204
4952
4953
4954
class HybridPowerStationUserCollection:
4955
    def __init__(self):
4956
        """Initializes Class"""
4957
        pass
4958
4959
    @staticmethod
4960
    def on_options(req, resp, id_):
4961
        resp.status = falcon.HTTP_200
4962
4963
    @staticmethod
4964
    def on_get(req, resp, id_):
4965
        access_control(req)
4966
        if not id_.isdigit() or int(id_) <= 0:
4967
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4968
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
4969
4970
        cnx = mysql.connector.connect(**config.myems_system_db)
4971
        cursor = cnx.cursor()
4972
        cursor.execute(" SELECT name "
4973
                       " FROM tbl_hybrid_power_stations "
4974
                       " WHERE id = %s ", (id_,))
4975
        if cursor.fetchone() is None:
4976
            cursor.close()
4977
            cnx.close()
4978
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4979
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
4980
4981
        query = (" SELECT u.id, u.name, u.uuid "
4982
                 " FROM tbl_hybrid_power_stations m, tbl_hybrid_power_stations_users mu, "
4983
                 + config.myems_user_db['database'] + ".tbl_users u "
4984
                 " WHERE mu.hybrid_power_station_id = m.id AND u.id = mu.user_id AND m.id = %s "
4985
                 " ORDER BY u.id ")
4986
        cursor.execute(query, (id_,))
4987
        rows = cursor.fetchall()
4988
        result = list()
4989
        if rows is not None and len(rows) > 0:
4990
            for row in rows:
4991
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
4992
                result.append(meta_result)
4993
4994
        cursor.close()
4995
        cnx.close()
4996
        resp.text = json.dumps(result)
4997
4998
    @staticmethod
4999
    @user_logger
5000
    def on_post(req, resp, id_):
5001
        """Handles POST requests"""
5002
        admin_control(req)
5003
        try:
5004
            raw_json = req.stream.read().decode('utf-8')
5005
        except Exception as ex:
5006
            raise falcon.HTTPError(status=falcon.HTTP_400,
5007
                                   title='API.BAD_REQUEST',
5008
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5009
5010
        if not id_.isdigit() or int(id_) <= 0:
5011
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5012
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
5013
5014
        new_values = json.loads(raw_json)
5015
        if 'user_id' not in new_values['data'].keys() or \
5016
                not isinstance(new_values['data']['user_id'], int) or \
5017
                new_values['data']['user_id'] <= 0:
5018
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5019
                                   description='API.INVALID_USER_ID')
5020
        user_id = new_values['data']['user_id']
5021
        cnx = mysql.connector.connect(**config.myems_system_db)
5022
        cursor = cnx.cursor()
5023
        cursor.execute(" SELECT name "
5024
                       " FROM tbl_hybrid_power_stations "
5025
                       " WHERE id = %s ", (id_,))
5026
        if cursor.fetchone() is None:
5027
            cursor.close()
5028
            cnx.close()
5029
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5030
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
5031
5032
        cnx_user = mysql.connector.connect(**config.myems_user_db)
5033
        cursor_user = cnx_user.cursor()
5034
        cursor_user.execute(" SELECT name"
5035
                            " FROM tbl_users "
5036
                            " WHERE id = %s ", (user_id,))
5037
        if cursor_user.fetchone() is None:
5038
            cursor_user.close()
5039
            cnx_user.close()
5040
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5041
                                   description='API.USER_NOT_FOUND')
5042
        query = (" SELECT id "
5043
                 " FROM tbl_hybrid_power_stations_users "
5044
                 " WHERE hybrid_power_station_id = %s AND user_id = %s")
5045
        cursor.execute(query, (id_, user_id,))
5046
        if cursor.fetchone() is not None:
5047
            cursor.close()
5048
            cnx.close()
5049
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5050
                                   description='API.HYBRID_POWER_STATION_USER_RELATION_EXISTS')
5051
        add_row = (" INSERT INTO tbl_hybrid_power_stations_users (hybrid_power_station_id, user_id) "
5052
                   " VALUES (%s, %s) ")
5053
        cursor.execute(add_row, (id_, user_id,))
5054
        cnx.commit()
5055
        cursor.close()
5056
        cnx.close()
5057
        cursor_user.close()
5058
        cnx_user.close()
5059
5060
        resp.status = falcon.HTTP_201
5061
        resp.location = '/hybridpowerstations/' + str(id_) + '/users/' + str(user_id)
5062
5063
5064
class HybridPowerStationUserItem:

myems-api/core/microgrid.py 1 location

@@ 4953-5060 (lines=108) @@
4950
        resp.status = falcon.HTTP_204
4951
4952
4953
class MicrogridUserCollection:
4954
    def __init__(self):
4955
        """Initializes Class"""
4956
        pass
4957
4958
    @staticmethod
4959
    def on_options(req, resp, id_):
4960
        resp.status = falcon.HTTP_200
4961
4962
    @staticmethod
4963
    def on_get(req, resp, id_):
4964
        access_control(req)
4965
        if not id_.isdigit() or int(id_) <= 0:
4966
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4967
                                   description='API.INVALID_MICROGRID_ID')
4968
4969
        cnx = mysql.connector.connect(**config.myems_system_db)
4970
        cursor = cnx.cursor()
4971
        cursor.execute(" SELECT name "
4972
                       " FROM tbl_microgrids "
4973
                       " WHERE id = %s ", (id_,))
4974
        if cursor.fetchone() is None:
4975
            cursor.close()
4976
            cnx.close()
4977
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4978
                                   description='API.MICROGRID_NOT_FOUND')
4979
4980
        query = (" SELECT u.id, u.name, u.uuid "
4981
                 " FROM tbl_microgrids m, tbl_microgrids_users mu, "
4982
                 + config.myems_user_db['database'] + ".tbl_users u "
4983
                 " WHERE mu.microgrid_id = m.id AND u.id = mu.user_id AND m.id = %s "
4984
                 " ORDER BY u.id ")
4985
        cursor.execute(query, (id_,))
4986
        rows = cursor.fetchall()
4987
        result = list()
4988
        if rows is not None and len(rows) > 0:
4989
            for row in rows:
4990
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
4991
                result.append(meta_result)
4992
4993
        cursor.close()
4994
        cnx.close()
4995
        resp.text = json.dumps(result)
4996
4997
    @staticmethod
4998
    @user_logger
4999
    def on_post(req, resp, id_):
5000
        """Handles POST requests"""
5001
        admin_control(req)
5002
        try:
5003
            raw_json = req.stream.read().decode('utf-8')
5004
        except Exception as ex:
5005
            raise falcon.HTTPError(status=falcon.HTTP_400,
5006
                                   title='API.BAD_REQUEST',
5007
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5008
5009
        if not id_.isdigit() or int(id_) <= 0:
5010
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5011
                                   description='API.INVALID_MICROGRID_ID')
5012
5013
        new_values = json.loads(raw_json)
5014
        if 'user_id' not in new_values['data'].keys() or \
5015
                not isinstance(new_values['data']['user_id'], int) or \
5016
                new_values['data']['user_id'] <= 0:
5017
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5018
                                   description='API.INVALID_USER_ID')
5019
        user_id = new_values['data']['user_id']
5020
        cnx = mysql.connector.connect(**config.myems_system_db)
5021
        cursor = cnx.cursor()
5022
        cursor.execute(" SELECT name "
5023
                       " from tbl_microgrids "
5024
                       " WHERE id = %s ", (id_,))
5025
        if cursor.fetchone() is None:
5026
            cursor.close()
5027
            cnx.close()
5028
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5029
                                   description='API.MICROGRID_NOT_FOUND')
5030
5031
        cnx_user = mysql.connector.connect(**config.myems_user_db)
5032
        cursor_user = cnx_user.cursor()
5033
        cursor_user.execute(" SELECT name"
5034
                            " FROM tbl_users "
5035
                            " WHERE id = %s ", (user_id,))
5036
        if cursor_user.fetchone() is None:
5037
            cursor_user.close()
5038
            cnx_user.close()
5039
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5040
                                   description='API.USER_NOT_FOUND')
5041
        query = (" SELECT id "
5042
                 " FROM tbl_microgrids_users "
5043
                 " WHERE microgrid_id = %s AND user_id = %s")
5044
        cursor.execute(query, (id_, user_id,))
5045
        if cursor.fetchone() is not None:
5046
            cursor.close()
5047
            cnx.close()
5048
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5049
                                   description='API.MICROGRID_USER_RELATION_EXISTS')
5050
        add_row = (" INSERT INTO tbl_microgrids_users (microgrid_id, user_id) "
5051
                   " VALUES (%s, %s) ")
5052
        cursor.execute(add_row, (id_, user_id,))
5053
        cnx.commit()
5054
        cursor.close()
5055
        cnx.close()
5056
        cursor_user.close()
5057
        cnx_user.close()
5058
5059
        resp.status = falcon.HTTP_201
5060
        resp.location = '/microgrids/' + str(id_) + '/users/' + str(user_id)
5061
5062
5063
class MicrogridUserItem:

myems-api/core/photovoltaicpowerstation.py 1 location

@@ 4798-4905 (lines=108) @@
4795
        resp.status = falcon.HTTP_200
4796
4797
4798
class PhotovoltaicPowerStationUserCollection:
4799
    def __init__(self):
4800
        """Initializes Class"""
4801
        pass
4802
4803
    @staticmethod
4804
    def on_options(req, resp, id_):
4805
        resp.status = falcon.HTTP_200
4806
4807
    @staticmethod
4808
    def on_get(req, resp, id_):
4809
        access_control(req)
4810
        if not id_.isdigit() or int(id_) <= 0:
4811
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4812
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
4813
4814
        cnx = mysql.connector.connect(**config.myems_system_db)
4815
        cursor = cnx.cursor()
4816
        cursor.execute(" SELECT name "
4817
                       " FROM tbl_photovoltaic_power_stations "
4818
                       " WHERE id = %s ", (id_,))
4819
        if cursor.fetchone() is None:
4820
            cursor.close()
4821
            cnx.close()
4822
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4823
                                   description='API.PHOTOVOLTAIC_POWER_STATION_NOT_FOUND')
4824
4825
        query = (" SELECT u.id, u.name, u.uuid "
4826
                 " FROM tbl_photovoltaic_power_stations m, tbl_photovoltaic_power_stations_users mu, "
4827
                 + config.myems_user_db['database'] + ".tbl_users u "
4828
                 " WHERE mu.photovoltaic_power_station_id = m.id AND u.id = mu.user_id AND m.id = %s "
4829
                 " ORDER BY u.id ")
4830
        cursor.execute(query, (id_,))
4831
        rows = cursor.fetchall()
4832
        result = list()
4833
        if rows is not None and len(rows) > 0:
4834
            for row in rows:
4835
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
4836
                result.append(meta_result)
4837
4838
        cursor.close()
4839
        cnx.close()
4840
        resp.text = json.dumps(result)
4841
4842
    @staticmethod
4843
    @user_logger
4844
    def on_post(req, resp, id_):
4845
        """Handles POST requests"""
4846
        admin_control(req)
4847
        try:
4848
            raw_json = req.stream.read().decode('utf-8')
4849
        except Exception as ex:
4850
            raise falcon.HTTPError(status=falcon.HTTP_400,
4851
                                   title='API.BAD_REQUEST',
4852
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4853
4854
        if not id_.isdigit() or int(id_) <= 0:
4855
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4856
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
4857
4858
        new_values = json.loads(raw_json)
4859
        if 'user_id' not in new_values['data'].keys() or \
4860
                not isinstance(new_values['data']['user_id'], int) or \
4861
                new_values['data']['user_id'] <= 0:
4862
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4863
                                   description='API.INVALID_USER_ID')
4864
        user_id = new_values['data']['user_id']
4865
        cnx = mysql.connector.connect(**config.myems_system_db)
4866
        cursor = cnx.cursor()
4867
        cursor.execute(" SELECT name "
4868
                       " FROM tbl_photovoltaic_power_stations "
4869
                       " WHERE id = %s ", (id_,))
4870
        if cursor.fetchone() is None:
4871
            cursor.close()
4872
            cnx.close()
4873
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4874
                                   description='API.PHOTOVOLTAIC_POWER_STATION_NOT_FOUND')
4875
4876
        cnx_user = mysql.connector.connect(**config.myems_user_db)
4877
        cursor_user = cnx_user.cursor()
4878
        cursor_user.execute(" SELECT name"
4879
                            " FROM tbl_users "
4880
                            " WHERE id = %s ", (user_id,))
4881
        if cursor_user.fetchone() is None:
4882
            cursor_user.close()
4883
            cnx_user.close()
4884
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4885
                                   description='API.USER_NOT_FOUND')
4886
        query = (" SELECT id "
4887
                 " FROM tbl_photovoltaic_power_stations_users "
4888
                 " WHERE photovoltaic_power_station_id = %s AND user_id = %s")
4889
        cursor.execute(query, (id_, user_id,))
4890
        if cursor.fetchone() is not None:
4891
            cursor.close()
4892
            cnx.close()
4893
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4894
                                   description='API.PHOTOVOLTAIC_POWER_STATION_USER_RELATION_EXISTS')
4895
        add_row = (" INSERT INTO tbl_photovoltaic_power_stations_users (photovoltaic_power_station_id, user_id) "
4896
                   " VALUES (%s, %s) ")
4897
        cursor.execute(add_row, (id_, user_id,))
4898
        cnx.commit()
4899
        cursor.close()
4900
        cnx.close()
4901
        cursor_user.close()
4902
        cnx_user.close()
4903
4904
        resp.status = falcon.HTTP_201
4905
        resp.location = '/photovoltaicpowerstations/' + str(id_) + '/users/' + str(user_id)
4906
4907
4908
class PhotovoltaicPowerStationUserItem:

myems-api/core/energystoragepowerstation.py 1 location

@@ 897-1004 (lines=108) @@
894
        resp.status = falcon.HTTP_204
895
896
897
class EnergyStoragePowerStationUserCollection:
898
    def __init__(self):
899
        """Initializes Class"""
900
        pass
901
902
    @staticmethod
903
    def on_options(req, resp, id_):
904
        resp.status = falcon.HTTP_200
905
906
    @staticmethod
907
    def on_get(req, resp, id_):
908
        access_control(req)
909
        if not id_.isdigit() or int(id_) <= 0:
910
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
911
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
912
913
        cnx = mysql.connector.connect(**config.myems_system_db)
914
        cursor = cnx.cursor()
915
        cursor.execute(" SELECT name "
916
                       " FROM tbl_energy_storage_power_stations "
917
                       " WHERE id = %s ", (id_,))
918
        if cursor.fetchone() is None:
919
            cursor.close()
920
            cnx.close()
921
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
922
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
923
924
        query = (" SELECT u.id, u.name, u.uuid "
925
                 " FROM tbl_energy_storage_power_stations m, tbl_energy_storage_power_stations_users mu, "
926
                 + config.myems_user_db['database'] + ".tbl_users u "
927
                 " WHERE mu.energy_storage_power_station_id = m.id AND u.id = mu.user_id AND m.id = %s "
928
                 " ORDER BY u.id ")
929
        cursor.execute(query, (id_,))
930
        rows = cursor.fetchall()
931
        result = list()
932
        if rows is not None and len(rows) > 0:
933
            for row in rows:
934
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
935
                result.append(meta_result)
936
937
        cursor.close()
938
        cnx.close()
939
        resp.text = json.dumps(result)
940
941
    @staticmethod
942
    @user_logger
943
    def on_post(req, resp, id_):
944
        """Handles POST requests"""
945
        admin_control(req)
946
        try:
947
            raw_json = req.stream.read().decode('utf-8')
948
        except Exception as ex:
949
            raise falcon.HTTPError(status=falcon.HTTP_400,
950
                                   title='API.BAD_REQUEST',
951
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
952
953
        if not id_.isdigit() or int(id_) <= 0:
954
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
955
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
956
957
        new_values = json.loads(raw_json)
958
        if 'user_id' not in new_values['data'].keys() or \
959
                not isinstance(new_values['data']['user_id'], int) or \
960
                new_values['data']['user_id'] <= 0:
961
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
962
                                   description='API.INVALID_USER_ID')
963
        user_id = new_values['data']['user_id']
964
        cnx = mysql.connector.connect(**config.myems_system_db)
965
        cursor = cnx.cursor()
966
        cursor.execute(" SELECT name "
967
                       " FROM tbl_energy_storage_power_stations "
968
                       " WHERE id = %s ", (id_,))
969
        if cursor.fetchone() is None:
970
            cursor.close()
971
            cnx.close()
972
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
973
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
974
975
        cnx_user = mysql.connector.connect(**config.myems_user_db)
976
        cursor_user = cnx_user.cursor()
977
        cursor_user.execute(" SELECT name"
978
                            " FROM tbl_users "
979
                            " WHERE id = %s ", (user_id,))
980
        if cursor_user.fetchone() is None:
981
            cursor_user.close()
982
            cnx_user.close()
983
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
984
                                   description='API.USER_NOT_FOUND')
985
        query = (" SELECT id "
986
                 " FROM tbl_energy_storage_power_stations_users "
987
                 " WHERE energy_storage_power_station_id = %s AND user_id = %s")
988
        cursor.execute(query, (id_, user_id,))
989
        if cursor.fetchone() is not None:
990
            cursor.close()
991
            cnx.close()
992
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
993
                                   description='API.ENERGY_STORAGE_POWER_STATION_USER_RELATION_EXISTS')
994
        add_row = (" INSERT INTO tbl_energy_storage_power_stations_users (energy_storage_power_station_id, user_id) "
995
                   " VALUES (%s, %s) ")
996
        cursor.execute(add_row, (id_, user_id,))
997
        cnx.commit()
998
        cursor.close()
999
        cnx.close()
1000
        cursor_user.close()
1001
        cnx_user.close()
1002
1003
        resp.status = falcon.HTTP_201
1004
        resp.location = '/energystoragepowerstations/' + str(id_) + '/users/' + str(user_id)
1005
1006
1007
class EnergyStoragePowerStationUserItem: