Code Duplication    Length = 208-213 lines in 2 locations

myems-api/core/energystoragecontainer.py 1 location

@@ 2364-2576 (lines=213) @@
2361
        resp.status = falcon.HTTP_204
2362
2363
2364
class EnergyStorageContainerGridCollection:
2365
    def __init__(self):
2366
        """Initializes Class"""
2367
        pass
2368
2369
    @staticmethod
2370
    def on_options(req, resp, id_):
2371
        _=req
2372
        resp.status = falcon.HTTP_200
2373
        _=id_
2374
    @staticmethod
2375
    def on_get(req, resp, id_):
2376
        access_control(req)
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_ENERGY_STORAGE_CONTAINER_ID')
2380
2381
        cnx = mysql.connector.connect(**config.myems_system_db)
2382
        cursor = cnx.cursor()
2383
2384
        cursor.execute(" SELECT name "
2385
                       " FROM tbl_energy_storage_containers "
2386
                       " WHERE id = %s ", (id_,))
2387
        if cursor.fetchone() is None:
2388
            cursor.close()
2389
            cnx.close()
2390
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2391
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2392
2393
        # query meter dict
2394
        query = (" SELECT id, name, uuid "
2395
                 " FROM tbl_meters ")
2396
        cursor.execute(query)
2397
        rows_meters = cursor.fetchall()
2398
2399
        meter_dict = dict()
2400
        if rows_meters is not None and len(rows_meters) > 0:
2401
            for row in rows_meters:
2402
                meter_dict[row[0]] = {"id": row[0],
2403
                                      "name": row[1],
2404
                                      "uuid": row[2]}
2405
        # query point dict
2406
        query = (" SELECT id, name "
2407
                 " FROM tbl_points ")
2408
        cursor.execute(query)
2409
        rows_points = cursor.fetchall()
2410
2411
        point_dict = dict()
2412
        if rows_points is not None and len(rows_points) > 0:
2413
            for row in rows_points:
2414
                point_dict[row[0]] = {"id": row[0],
2415
                                      "name": row[1]}
2416
2417
        query = (" SELECT id, name, uuid, "
2418
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2419
                 " FROM tbl_energy_storage_containers_grids "
2420
                 " WHERE energy_storage_container_id = %s "
2421
                 " ORDER BY name ")
2422
        cursor.execute(query, (id_,))
2423
        rows = cursor.fetchall()
2424
2425
        result = list()
2426
        if rows is not None and len(rows) > 0:
2427
            for row in rows:
2428
                meta_result = {"id": row[0],
2429
                               "name": row[1],
2430
                               "uuid": row[2],
2431
                               "power_point": point_dict.get(row[3]),
2432
                               "buy_meter": meter_dict.get(row[4]),
2433
                               "sell_meter": meter_dict.get(row[5]),
2434
                               "capacity": row[6]
2435
                               }
2436
                result.append(meta_result)
2437
2438
        resp.text = json.dumps(result)
2439
2440
    @staticmethod
2441
    @user_logger
2442
    def on_post(req, resp, id_):
2443
        """Handles POST requests"""
2444
        admin_control(req)
2445
        try:
2446
            raw_json = req.stream.read().decode('utf-8')
2447
        except Exception as ex:
2448
            print(str(ex))
2449
            raise falcon.HTTPError(status=falcon.HTTP_400,
2450
                                   title='API.BAD_REQUEST',
2451
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2452
        if not id_.isdigit() or int(id_) <= 0:
2453
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2454
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2455
2456
        cnx = mysql.connector.connect(**config.myems_system_db)
2457
        cursor = cnx.cursor()
2458
2459
        cursor.execute(" SELECT name "
2460
                       " FROM tbl_energy_storage_containers "
2461
                       " WHERE id = %s ", (id_,))
2462
        if cursor.fetchone() is None:
2463
            cursor.close()
2464
            cnx.close()
2465
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2466
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2467
2468
        new_values = json.loads(raw_json)
2469
2470
        if 'name' not in new_values['data'].keys() or \
2471
                not isinstance(new_values['data']['name'], str) or \
2472
                len(str.strip(new_values['data']['name'])) == 0:
2473
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2474
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_GRID_NAME')
2475
        name = str.strip(new_values['data']['name'])
2476
2477
        if 'power_point_id' not in new_values['data'].keys() or \
2478
                not isinstance(new_values['data']['power_point_id'], int) or \
2479
                new_values['data']['power_point_id'] <= 0:
2480
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2481
                                   description='API.INVALID_POWER_POINT_ID')
2482
        power_point_id = new_values['data']['power_point_id']
2483
2484
        if 'buy_meter_id' not in new_values['data'].keys() or \
2485
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2486
                new_values['data']['buy_meter_id'] <= 0:
2487
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2488
                                   description='API.INVALID_BUY_METER_ID')
2489
        buy_meter_id = new_values['data']['buy_meter_id']
2490
2491
        if 'sell_meter_id' not in new_values['data'].keys() or \
2492
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2493
                new_values['data']['sell_meter_id'] <= 0:
2494
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2495
                                   description='API.INVALID_SELL_METER_ID')
2496
        sell_meter_id = new_values['data']['sell_meter_id']
2497
2498
        if 'capacity' not in new_values['data'].keys() or \
2499
                not (isinstance(new_values['data']['capacity'], float) or
2500
                     isinstance(new_values['data']['capacity'], int)):
2501
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2502
                                   description='API.INVALID_CAPACITY')
2503
        capacity = Decimal(new_values['data']['capacity'])
2504
2505
        cnx = mysql.connector.connect(**config.myems_system_db)
2506
        cursor = cnx.cursor()
2507
2508
        cursor.execute(" SELECT name "
2509
                       " FROM tbl_energy_storage_containers "
2510
                       " WHERE id = %s ",
2511
                       (id_,))
2512
        if cursor.fetchone() is None:
2513
            cursor.close()
2514
            cnx.close()
2515
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2516
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2517
2518
        cursor.execute(" SELECT name "
2519
                       " FROM tbl_energy_storage_containers_grids "
2520
                       " WHERE energy_storage_container_id = %s AND name = %s ",
2521
                       (id_, name,))
2522
        if cursor.fetchone() is not None:
2523
            cursor.close()
2524
            cnx.close()
2525
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2526
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NAME_IS_ALREADY_IN_USE')
2527
2528
        cursor.execute(" SELECT name "
2529
                       " FROM tbl_points "
2530
                       " WHERE id = %s ",
2531
                       (power_point_id,))
2532
        if cursor.fetchone() is None:
2533
            cursor.close()
2534
            cnx.close()
2535
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2536
                                   description='API.POWER_POINT_NOT_FOUND')
2537
2538
        cursor.execute(" SELECT name "
2539
                       " FROM tbl_meters "
2540
                       " WHERE id = %s ",
2541
                       (buy_meter_id,))
2542
        if cursor.fetchone() is None:
2543
            cursor.close()
2544
            cnx.close()
2545
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2546
                                   description='API.BUY_METER_NOT_FOUND')
2547
2548
        cursor.execute(" SELECT name "
2549
                       " FROM tbl_meters "
2550
                       " WHERE id = %s ",
2551
                       (sell_meter_id,))
2552
        if cursor.fetchone() is None:
2553
            cursor.close()
2554
            cnx.close()
2555
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2556
                                   description='API.SELL_METER_NOT_FOUND')
2557
2558
        add_values = (" INSERT INTO tbl_energy_storage_containers_grids "
2559
                      "    (name, uuid, energy_storage_container_id, power_point_id, "
2560
                      "     buy_meter_id, sell_meter_id, capacity) "
2561
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2562
        cursor.execute(add_values, (name,
2563
                                    str(uuid.uuid4()),
2564
                                    id_,
2565
                                    power_point_id,
2566
                                    buy_meter_id,
2567
                                    sell_meter_id,
2568
                                    capacity
2569
                                    ))
2570
        new_id = cursor.lastrowid
2571
        cnx.commit()
2572
        cursor.close()
2573
        cnx.close()
2574
2575
        resp.status = falcon.HTTP_201
2576
        resp.location = '/energystoragecontainers/' + str(id_) + '/grids/' + str(new_id)
2577
2578
2579
class EnergyStorageContainerGridItem:

myems-api/core/microgrid.py 1 location

@@ 2148-2355 (lines=208) @@
2145
        resp.status = falcon.HTTP_200
2146
2147
2148
class MicrogridGridCollection:
2149
    def __init__(self):
2150
        """Initializes MicrogridGridCollection"""
2151
        pass
2152
2153
    @staticmethod
2154
    def on_options(req, resp, id_):
2155
        resp.status = falcon.HTTP_200
2156
2157
    @staticmethod
2158
    def on_get(req, resp, id_):
2159
        access_control(req)
2160
        if not id_.isdigit() or int(id_) <= 0:
2161
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2162
                                   description='API.INVALID_MICROGRID_ID')
2163
2164
        cnx = mysql.connector.connect(**config.myems_system_db)
2165
        cursor = cnx.cursor()
2166
2167
        cursor.execute(" SELECT name "
2168
                       " FROM tbl_microgrids "
2169
                       " WHERE id = %s ", (id_,))
2170
        if cursor.fetchone() is None:
2171
            cursor.close()
2172
            cnx.close()
2173
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2174
                                   description='API.MICROGRID_NOT_FOUND')
2175
2176
        # query meter dict
2177
        query = (" SELECT id, name, uuid "
2178
                 " FROM tbl_meters ")
2179
        cursor.execute(query)
2180
        rows_meters = cursor.fetchall()
2181
2182
        meter_dict = dict()
2183
        if rows_meters is not None and len(rows_meters) > 0:
2184
            for row in rows_meters:
2185
                meter_dict[row[0]] = {"id": row[0],
2186
                                      "name": row[1],
2187
                                      "uuid": row[2]}
2188
        # query point dict
2189
        query = (" SELECT id, name "
2190
                 " FROM tbl_points ")
2191
        cursor.execute(query)
2192
        rows_points = cursor.fetchall()
2193
2194
        point_dict = dict()
2195
        if rows_points is not None and len(rows_points) > 0:
2196
            for row in rows_points:
2197
                point_dict[row[0]] = {"id": row[0],
2198
                                      "name": row[1]}
2199
2200
        query = (" SELECT id, name, uuid, "
2201
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2202
                 " FROM tbl_microgrids_grids "
2203
                 " WHERE microgrid_id = %s "
2204
                 " ORDER BY name ")
2205
        cursor.execute(query, (id_,))
2206
        rows = cursor.fetchall()
2207
2208
        result = list()
2209
        if rows is not None and len(rows) > 0:
2210
            for row in rows:
2211
                meta_result = {"id": row[0],
2212
                               "name": row[1],
2213
                               "uuid": row[2],
2214
                               "power_point": point_dict.get(row[3]),
2215
                               "buy_meter": meter_dict.get(row[4]),
2216
                               "sell_meter": meter_dict.get(row[5]),
2217
                               "capacity": row[6]}
2218
                result.append(meta_result)
2219
2220
        resp.text = json.dumps(result)
2221
2222
    @staticmethod
2223
    @user_logger
2224
    def on_post(req, resp, id_):
2225
        """Handles POST requests"""
2226
        admin_control(req)
2227
        try:
2228
            raw_json = req.stream.read().decode('utf-8')
2229
        except Exception as ex:
2230
            raise falcon.HTTPError(status=falcon.HTTP_400,
2231
                                   title='API.BAD_REQUEST',
2232
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2233
        if not id_.isdigit() or int(id_) <= 0:
2234
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2235
                                   description='API.INVALID_MICROGRID_ID')
2236
2237
        cnx = mysql.connector.connect(**config.myems_system_db)
2238
        cursor = cnx.cursor()
2239
2240
        cursor.execute(" SELECT name "
2241
                       " FROM tbl_microgrids "
2242
                       " WHERE id = %s ", (id_,))
2243
        if cursor.fetchone() is None:
2244
            cursor.close()
2245
            cnx.close()
2246
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2247
                                   description='API.MICROGRID_NOT_FOUND')
2248
2249
        new_values = json.loads(raw_json)
2250
2251
        if 'name' not in new_values['data'].keys() or \
2252
                not isinstance(new_values['data']['name'], str) or \
2253
                len(str.strip(new_values['data']['name'])) == 0:
2254
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2255
                                   description='API.INVALID_MICROGRID_GRID_NAME')
2256
        name = str.strip(new_values['data']['name'])
2257
2258
        if 'power_point_id' not in new_values['data'].keys() or \
2259
                not isinstance(new_values['data']['power_point_id'], int) or \
2260
                new_values['data']['power_point_id'] <= 0:
2261
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2262
                                   description='API.INVALID_POWER_POINT_ID')
2263
        power_point_id = new_values['data']['power_point_id']
2264
2265
        if 'buy_meter_id' not in new_values['data'].keys() or \
2266
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2267
                new_values['data']['buy_meter_id'] <= 0:
2268
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2269
                                   description='API.INVALID_BUY_METER_ID')
2270
        buy_meter_id = new_values['data']['buy_meter_id']
2271
2272
        if 'sell_meter_id' not in new_values['data'].keys() or \
2273
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2274
                new_values['data']['sell_meter_id'] <= 0:
2275
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2276
                                   description='API.INVALID_SELL_METER_ID')
2277
        sell_meter_id = new_values['data']['sell_meter_id']
2278
2279
        if 'capacity' not in new_values['data'].keys() or \
2280
                not (isinstance(new_values['data']['capacity'], float) or
2281
                     isinstance(new_values['data']['capacity'], int)):
2282
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2283
                                   description='API.INVALID_CAPACITY')
2284
        capacity = float(new_values['data']['capacity'])
2285
2286
        cnx = mysql.connector.connect(**config.myems_system_db)
2287
        cursor = cnx.cursor()
2288
2289
        cursor.execute(" SELECT name "
2290
                       " FROM tbl_microgrids "
2291
                       " WHERE id = %s ",
2292
                       (id_,))
2293
        if cursor.fetchone() is None:
2294
            cursor.close()
2295
            cnx.close()
2296
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2297
                                   description='API.MICROGRID_NOT_FOUND')
2298
2299
        cursor.execute(" SELECT name "
2300
                       " FROM tbl_microgrids_grids "
2301
                       " WHERE microgrid_id = %s AND name = %s ",
2302
                       (id_, name,))
2303
        if cursor.fetchone() is not None:
2304
            cursor.close()
2305
            cnx.close()
2306
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2307
                                   description='API.MICROGRID_GRID_NAME_IS_ALREADY_IN_USE')
2308
2309
        cursor.execute(" SELECT name "
2310
                       " FROM tbl_points "
2311
                       " WHERE id = %s ",
2312
                       (power_point_id,))
2313
        if cursor.fetchone() is None:
2314
            cursor.close()
2315
            cnx.close()
2316
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2317
                                   description='API.POWER_POINT_NOT_FOUND')
2318
2319
        cursor.execute(" SELECT name "
2320
                       " FROM tbl_meters "
2321
                       " WHERE id = %s ",
2322
                       (buy_meter_id,))
2323
        if cursor.fetchone() is None:
2324
            cursor.close()
2325
            cnx.close()
2326
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2327
                                   description='API.BUY_METER_NOT_FOUND')
2328
2329
        cursor.execute(" SELECT name "
2330
                       " FROM tbl_meters "
2331
                       " WHERE id = %s ",
2332
                       (sell_meter_id,))
2333
        if cursor.fetchone() is None:
2334
            cursor.close()
2335
            cnx.close()
2336
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2337
                                   description='API.SELL_METER_NOT_FOUND')
2338
2339
        add_values = (" INSERT INTO tbl_microgrids_grids "
2340
                      "    (name, uuid, microgrid_id, power_point_id, buy_meter_id, sell_meter_id, capacity) "
2341
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2342
        cursor.execute(add_values, (name,
2343
                                    str(uuid.uuid4()),
2344
                                    id_,
2345
                                    power_point_id,
2346
                                    buy_meter_id,
2347
                                    sell_meter_id,
2348
                                    capacity))
2349
        new_id = cursor.lastrowid
2350
        cnx.commit()
2351
        cursor.close()
2352
        cnx.close()
2353
2354
        resp.status = falcon.HTTP_201
2355
        resp.location = '/microgrids/' + str(id_) + '/grids/' + str(new_id)
2356
2357
2358
class MicrogridGridItem: