Code Duplication    Length = 225-226 lines in 2 locations

myems-api/core/hybridpowerstation.py 2 locations

@@ 2235-2460 (lines=226) @@
2232
        resp.location = '/hybridpowerstation/' + str(id_) + '/generators/' + str(new_id)
2233
2234
2235
class HybridPowerStationGeneratorItem:
2236
    def __init__(self):
2237
        """Initializes Class"""
2238
        pass
2239
2240
    @staticmethod
2241
    def on_options(req, resp, id_, gid):
2242
        resp.status = falcon.HTTP_200
2243
2244
    @staticmethod
2245
    def on_get(req, resp, id_, gid):
2246
        access_control(req)
2247
        if not id_.isdigit() or int(id_) <= 0:
2248
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2249
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
2250
        if not gid.isdigit() or int(gid) <= 0:
2251
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2252
                                   description='API.INVALID_HYBRID_POWER_STATION_GENERATOR_ID')
2253
2254
        cnx = mysql.connector.connect(**config.myems_system_db)
2255
        cursor = cnx.cursor()
2256
2257
        cursor.execute(" SELECT name "
2258
                       " FROM tbl_hybrid_power_stations "
2259
                       " WHERE id = %s ", (id_,))
2260
        if cursor.fetchone() is None:
2261
            cursor.close()
2262
            cnx.close()
2263
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2264
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
2265
2266
        query = (" SELECT id, name, uuid "
2267
                 " FROM tbl_hybrid_power_stations ")
2268
        cursor.execute(query)
2269
        rows_hybridpowerstations = cursor.fetchall()
2270
2271
        hybrid_power_station_dict = dict()
2272
        if rows_hybridpowerstations is not None and len(rows_hybridpowerstations) > 0:
2273
            for row in rows_hybridpowerstations:
2274
                hybrid_power_station_dict[row[0]] = {"id": row[0],
2275
                                                     "name": row[1],
2276
                                                     "uuid": row[2]}
2277
        query = (" SELECT id, name, uuid "
2278
                 " FROM tbl_meters ")
2279
        cursor.execute(query)
2280
        rows_meters = cursor.fetchall()
2281
2282
        meter_dict = dict()
2283
        if rows_meters is not None and len(rows_meters) > 0:
2284
            for row in rows_meters:
2285
                meter_dict[row[0]] = {"id": row[0],
2286
                                      "name": row[1],
2287
                                      "uuid": row[2]}
2288
        # query point dict
2289
        query = (" SELECT id, name "
2290
                 " FROM tbl_points ")
2291
        cursor.execute(query)
2292
        rows_points = cursor.fetchall()
2293
2294
        point_dict = dict()
2295
        if rows_points is not None and len(rows_points) > 0:
2296
            for row in rows_points:
2297
                point_dict[row[0]] = {"id": row[0],
2298
                                      "name": row[1]}
2299
2300
        query = (" SELECT id, name, uuid, hybrid_power_station_id, operating_status_point_id, "
2301
                 "        fuel_consumption_meter_id, "
2302
                 "        power_generation_meter_id "
2303
                 " FROM tbl_hybrid_power_stations_generators "
2304
                 " WHERE id = %s ")
2305
        cursor.execute(query, (gid,))
2306
        row = cursor.fetchone()
2307
        cursor.close()
2308
        cnx.close()
2309
2310
        if row is None:
2311
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2312
                                   description='API.HYBRID_POWER_STATION_GENERATOR_NOT_FOUND')
2313
        else:
2314
            meta_result = {"id": row[0],
2315
                           "name": row[1],
2316
                           "uuid": row[2],
2317
                           "hybrid_power_station": hybrid_power_station_dict.get(row[3]),
2318
                           "operating_status_point": point_dict.get(row[4]),
2319
                           "fuel_consumption_meter": meter_dict.get(row[5]),
2320
                           "power_generation_meter": meter_dict.get(row[6]),
2321
                           }
2322
2323
        resp.text = json.dumps(meta_result)
2324
2325
    @staticmethod
2326
    @user_logger
2327
    def on_delete(req, resp, id_, gid):
2328
        admin_control(req)
2329
        if not id_.isdigit() or int(id_) <= 0:
2330
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2331
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
2332
        if not gid.isdigit() or int(gid) <= 0:
2333
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2334
                                   description='API.INVALID_HYBRID_POWER_STATION_GENERATOR_ID')
2335
2336
        cnx = mysql.connector.connect(**config.myems_system_db)
2337
        cursor = cnx.cursor()
2338
2339
        cursor.execute(" SELECT name "
2340
                       " FROM tbl_hybrid_power_stations "
2341
                       " WHERE id = %s ", (id_,))
2342
        if cursor.fetchone() is None:
2343
            cursor.close()
2344
            cnx.close()
2345
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2346
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
2347
2348
        cursor.execute(" SELECT name "
2349
                       " FROM tbl_hybrid_power_stations_generators "
2350
                       " WHERE id = %s ", (gid,))
2351
        if cursor.fetchone() is None:
2352
            cursor.close()
2353
            cnx.close()
2354
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2355
                                   description='API.HYBRID_POWER_STATION_GENERATOR_NOT_FOUND')
2356
2357
        cursor.execute(" DELETE FROM tbl_hybrid_power_stations_generators "
2358
                       " WHERE id = %s ", (gid,))
2359
        cnx.commit()
2360
2361
        cursor.close()
2362
        cnx.close()
2363
2364
        resp.status = falcon.HTTP_204
2365
2366
    @staticmethod
2367
    @user_logger
2368
    def on_put(req, resp, id_, gid):
2369
        """Handles PUT requests"""
2370
        admin_control(req)
2371
        try:
2372
            raw_json = req.stream.read().decode('utf-8')
2373
        except Exception as ex:
2374
            raise falcon.HTTPError(status=falcon.HTTP_400,
2375
                                   title='API.BAD_REQUEST',
2376
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2377
        if not id_.isdigit() or int(id_) <= 0:
2378
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2379
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
2380
        if not gid.isdigit() or int(gid) <= 0:
2381
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2382
                                   description='API.INVALID_HYBRID_POWER_STATION_GENERATOR_ID')
2383
2384
        new_values = json.loads(raw_json)
2385
2386
        if 'name' not in new_values['data'].keys() or \
2387
                not isinstance(new_values['data']['name'], str) or \
2388
                len(str.strip(new_values['data']['name'])) == 0:
2389
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2390
                                   description='API.INVALID_HYBRID_POWER_STATION_GENERATOR_NAME')
2391
        name = str.strip(new_values['data']['name'])
2392
2393
        if 'operating_status_point_id' not in new_values['data'].keys() or \
2394
                not isinstance(new_values['data']['operating_status_point_id'], int) or \
2395
                new_values['data']['operating_status_point_id'] <= 0:
2396
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2397
                                   description='API.INVALID_OPERATING_STATUS_POINT_ID')
2398
        operating_status_point_id = new_values['data']['operating_status_point_id']
2399
2400
        if 'fuel_consumption_meter_id' not in new_values['data'].keys() or \
2401
                not isinstance(new_values['data']['fuel_consumption_meter_id'], int) or \
2402
                new_values['data']['fuel_consumption_meter_id'] <= 0:
2403
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2404
                                   description='API.INVALID_FUELCONSUMPTION_METER_ID')
2405
        fuel_consumption_meter_id = new_values['data']['fuel_consumption_meter_id']
2406
2407
        if 'power_generation_meter_id' not in new_values['data'].keys() or \
2408
                not isinstance(new_values['data']['power_generation_meter_id'], int) or \
2409
                new_values['data']['power_generation_meter_id'] <= 0:
2410
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2411
                                   description='API.INVALID_POWER_GENERATION_METER_ID')
2412
        power_generation_meter_id = new_values['data']['power_generation_meter_id']
2413
2414
        cnx = mysql.connector.connect(**config.myems_system_db)
2415
        cursor = cnx.cursor()
2416
2417
        cursor.execute(" SELECT name "
2418
                       " FROM tbl_hybrid_power_stations "
2419
                       " WHERE id = %s ", (id_,))
2420
        if cursor.fetchone() is None:
2421
            cursor.close()
2422
            cnx.close()
2423
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2424
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
2425
2426
        cursor.execute(" SELECT name "
2427
                       " FROM tbl_hybrid_power_stations_generators "
2428
                       " WHERE id = %s ", (gid,))
2429
        if cursor.fetchone() is None:
2430
            cursor.close()
2431
            cnx.close()
2432
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2433
                                   description='API.HYBRID_POWER_STATION_GENERATOR_NOT_FOUND')
2434
2435
        cursor.execute(" SELECT name "
2436
                       " FROM tbl_hybrid_power_stations_generators "
2437
                       " WHERE hybrid_power_station_id = %s AND name = %s AND id != %s ",
2438
                       (id_, name, gid))
2439
        if cursor.fetchone() is not None:
2440
            cursor.close()
2441
            cnx.close()
2442
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2443
                                   description='API.HYBRID_POWER_STATION_GENERATOR_NAME_IS_ALREADY_IN_USE')
2444
2445
        update_row = (" UPDATE tbl_hybrid_power_stations_generators "
2446
                      " SET name = %s, hybrid_power_station_id = %s, operating_status_point_id = %s, "
2447
                      "     fuel_consumption_meter_id = %s, power_generation_meter_id = %s "
2448
                      "     WHERE id = %s ")
2449
        cursor.execute(update_row, (name,
2450
                                    id_,
2451
                                    operating_status_point_id,
2452
                                    fuel_consumption_meter_id,
2453
                                    power_generation_meter_id,
2454
                                    gid))
2455
        cnx.commit()
2456
2457
        cursor.close()
2458
        cnx.close()
2459
2460
        resp.status = falcon.HTTP_200
2461
2462
2463
class HybridPowerStationGeneratorPointCollection:
@@ 3982-4206 (lines=225) @@
3979
        resp.location = '/hybridpowerstation/' + str(id_) + '/pcses/' + str(new_id)
3980
3981
3982
class HybridPowerStationPCSItem:
3983
    def __init__(self):
3984
        """Initializes Class"""
3985
        pass
3986
3987
    @staticmethod
3988
    def on_options(req, resp, id_, pcsid):
3989
        resp.status = falcon.HTTP_200
3990
3991
    @staticmethod
3992
    def on_get(req, resp, id_, pcsid):
3993
        access_control(req)
3994
        if not id_.isdigit() or int(id_) <= 0:
3995
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3996
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
3997
        if not pcsid.isdigit() or int(pcsid) <= 0:
3998
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3999
                                   description='API.INVALID_HYBRID_POWER_STATION_PCS_ID')
4000
4001
        cnx = mysql.connector.connect(**config.myems_system_db)
4002
        cursor = cnx.cursor()
4003
4004
        cursor.execute(" SELECT name "
4005
                       " FROM tbl_hybrid_power_stations "
4006
                       " WHERE id = %s ", (id_,))
4007
        if cursor.fetchone() is None:
4008
            cursor.close()
4009
            cnx.close()
4010
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4011
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
4012
4013
        query = (" SELECT id, name, uuid "
4014
                 " FROM tbl_hybrid_power_stations ")
4015
        cursor.execute(query)
4016
        rows_hybridpowerstations = cursor.fetchall()
4017
4018
        hybrid_power_station_dict = dict()
4019
        if rows_hybridpowerstations is not None and len(rows_hybridpowerstations) > 0:
4020
            for row in rows_hybridpowerstations:
4021
                hybrid_power_station_dict[row[0]] = {"id": row[0],
4022
                                                     "name": row[1],
4023
                                                     "uuid": row[2]}
4024
        query = (" SELECT id, name, uuid "
4025
                 " FROM tbl_meters ")
4026
        cursor.execute(query)
4027
        rows_meters = cursor.fetchall()
4028
4029
        meter_dict = dict()
4030
        if rows_meters is not None and len(rows_meters) > 0:
4031
            for row in rows_meters:
4032
                meter_dict[row[0]] = {"id": row[0],
4033
                                      "name": row[1],
4034
                                      "uuid": row[2]}
4035
        # query point dict
4036
        query = (" SELECT id, name "
4037
                 " FROM tbl_points ")
4038
        cursor.execute(query)
4039
        rows_points = cursor.fetchall()
4040
4041
        point_dict = dict()
4042
        if rows_points is not None and len(rows_points) > 0:
4043
            for row in rows_points:
4044
                point_dict[row[0]] = {"id": row[0],
4045
                                      "name": row[1]}
4046
4047
        query = (" SELECT id, name, uuid, hybrid_power_station_id, operating_status_point_id, charge_meter_id, "
4048
                 "        discharge_meter_id "
4049
                 " FROM tbl_hybrid_power_stations_pcses "
4050
                 " WHERE id = %s ")
4051
        cursor.execute(query, (pcsid,))
4052
        row = cursor.fetchone()
4053
        cursor.close()
4054
        cnx.close()
4055
4056
        if row is None:
4057
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4058
                                   description='API.HYBRID_POWER_STATION_PCS_NOT_FOUND')
4059
        else:
4060
            meta_result = {"id": row[0],
4061
                           "name": row[1],
4062
                           "uuid": row[2],
4063
                           "hybrid_power_station": hybrid_power_station_dict.get(row[3]),
4064
                           "operating_status_point": point_dict.get(row[4]),
4065
                           "charge_meter": meter_dict.get(row[5]),
4066
                           "discharge_meter": meter_dict.get(row[6]),
4067
                           }
4068
4069
        resp.text = json.dumps(meta_result)
4070
4071
    @staticmethod
4072
    @user_logger
4073
    def on_delete(req, resp, id_, pcsid):
4074
        admin_control(req)
4075
        if not id_.isdigit() or int(id_) <= 0:
4076
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4077
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
4078
        if not pcsid.isdigit() or int(pcsid) <= 0:
4079
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4080
                                   description='API.INVALID_HYBRID_POWER_STATION_PCS_ID')
4081
4082
        cnx = mysql.connector.connect(**config.myems_system_db)
4083
        cursor = cnx.cursor()
4084
4085
        cursor.execute(" SELECT name "
4086
                       " FROM tbl_hybrid_power_stations "
4087
                       " WHERE id = %s ", (id_,))
4088
        if cursor.fetchone() is None:
4089
            cursor.close()
4090
            cnx.close()
4091
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4092
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
4093
4094
        cursor.execute(" SELECT name "
4095
                       " FROM tbl_hybrid_power_stations_pcses "
4096
                       " WHERE id = %s ", (pcsid,))
4097
        if cursor.fetchone() is None:
4098
            cursor.close()
4099
            cnx.close()
4100
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4101
                                   description='API.HYBRID_POWER_STATION_PCS_NOT_FOUND')
4102
4103
        cursor.execute(" DELETE FROM tbl_hybrid_power_stations_pcses "
4104
                       " WHERE id = %s ", (pcsid,))
4105
        cnx.commit()
4106
4107
        cursor.close()
4108
        cnx.close()
4109
4110
        resp.status = falcon.HTTP_204
4111
4112
    @staticmethod
4113
    @user_logger
4114
    def on_put(req, resp, id_, pcsid):
4115
        """Handles PUT requests"""
4116
        admin_control(req)
4117
        try:
4118
            raw_json = req.stream.read().decode('utf-8')
4119
        except Exception as ex:
4120
            raise falcon.HTTPError(status=falcon.HTTP_400,
4121
                                   title='API.BAD_REQUEST',
4122
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4123
        if not id_.isdigit() or int(id_) <= 0:
4124
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4125
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
4126
        if not pcsid.isdigit() or int(pcsid) <= 0:
4127
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4128
                                   description='API.INVALID_HYBRID_POWER_STATION_PCS_ID')
4129
4130
        new_values = json.loads(raw_json)
4131
4132
        if 'name' not in new_values['data'].keys() or \
4133
                not isinstance(new_values['data']['name'], str) or \
4134
                len(str.strip(new_values['data']['name'])) == 0:
4135
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4136
                                   description='API.INVALID_HYBRID_POWER_STATION_PCS_NAME')
4137
        name = str.strip(new_values['data']['name'])
4138
4139
        if 'operating_status_point_id' not in new_values['data'].keys() or \
4140
                not isinstance(new_values['data']['operating_status_point_id'], int) or \
4141
                new_values['data']['operating_status_point_id'] <= 0:
4142
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4143
                                   description='API.INVALID_OPERATING_STATUS_POINT_ID')
4144
        operating_status_point_id = new_values['data']['operating_status_point_id']
4145
4146
        if 'charge_meter_id' not in new_values['data'].keys() or \
4147
                not isinstance(new_values['data']['charge_meter_id'], int) or \
4148
                new_values['data']['charge_meter_id'] <= 0:
4149
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4150
                                   description='API.INVALID_CHARGE_METER_ID')
4151
        charge_meter_id = new_values['data']['charge_meter_id']
4152
4153
        if 'discharge_meter_id' not in new_values['data'].keys() or \
4154
                not isinstance(new_values['data']['discharge_meter_id'], int) or \
4155
                new_values['data']['discharge_meter_id'] <= 0:
4156
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4157
                                   description='API.INVALID_DISCHARGE_METER_ID')
4158
        discharge_meter_id = new_values['data']['discharge_meter_id']
4159
4160
        cnx = mysql.connector.connect(**config.myems_system_db)
4161
        cursor = cnx.cursor()
4162
4163
        cursor.execute(" SELECT name "
4164
                       " FROM tbl_hybrid_power_stations "
4165
                       " WHERE id = %s ", (id_,))
4166
        if cursor.fetchone() is None:
4167
            cursor.close()
4168
            cnx.close()
4169
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4170
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
4171
4172
        cursor.execute(" SELECT name "
4173
                       " FROM tbl_hybrid_power_stations_pcses "
4174
                       " WHERE id = %s ", (pcsid,))
4175
        if cursor.fetchone() is None:
4176
            cursor.close()
4177
            cnx.close()
4178
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4179
                                   description='API.HYBRID_POWER_STATION_PCS_NOT_FOUND')
4180
4181
        cursor.execute(" SELECT name "
4182
                       " FROM tbl_hybrid_power_stations_pcses "
4183
                       " WHERE hybrid_power_station_id = %s AND name = %s AND id != %s ",
4184
                       (id_, name, pcsid))
4185
        if cursor.fetchone() is not None:
4186
            cursor.close()
4187
            cnx.close()
4188
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4189
                                   description='API.HYBRID_POWER_STATION_PCS_NAME_IS_ALREADY_IN_USE')
4190
4191
        update_row = (" UPDATE tbl_hybrid_power_stations_pcses "
4192
                      " SET name = %s, hybrid_power_station_id = %s, operating_status_point_id = %s, "
4193
                      "     charge_meter_id = %s, discharge_meter_id = %s "
4194
                      "     WHERE id = %s ")
4195
        cursor.execute(update_row, (name,
4196
                                    id_,
4197
                                    operating_status_point_id,
4198
                                    charge_meter_id,
4199
                                    discharge_meter_id,
4200
                                    pcsid))
4201
        cnx.commit()
4202
4203
        cursor.close()
4204
        cnx.close()
4205
4206
        resp.status = falcon.HTTP_200
4207
4208
4209
class HybridPowerStationPCSPointCollection: