| Total Complexity | 138 |
| Total Lines | 761 |
| Duplicated Lines | 24.44 % |
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like core.distributionsystem often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import uuid |
||
| 2 | from datetime import datetime, timedelta |
||
| 3 | import falcon |
||
| 4 | import mysql.connector |
||
| 5 | import simplejson as json |
||
| 6 | from core.useractivity import user_logger, admin_control, access_control, api_key_control |
||
| 7 | import config |
||
| 8 | |||
| 9 | |||
| 10 | class DistributionSystemCollection: |
||
| 11 | """ |
||
| 12 | Distribution System Collection Resource |
||
| 13 | |||
| 14 | This class handles CRUD operations for distribution system collection. |
||
| 15 | It provides endpoints for listing all distribution systems and creating new ones. |
||
| 16 | Distribution systems represent electrical distribution networks in the energy management system. |
||
| 17 | """ |
||
| 18 | def __init__(self): |
||
| 19 | """Initialize DistributionSystemCollection""" |
||
| 20 | pass |
||
| 21 | |||
| 22 | @staticmethod |
||
| 23 | def on_options(req, resp): |
||
| 24 | """Handle OPTIONS requests for CORS preflight""" |
||
| 25 | _ = req |
||
| 26 | resp.status = falcon.HTTP_200 |
||
| 27 | |||
| 28 | @staticmethod |
||
| 29 | def on_get(req, resp): |
||
| 30 | if 'API-KEY' not in req.headers or \ |
||
| 31 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 32 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 33 | access_control(req) |
||
| 34 | else: |
||
| 35 | api_key_control(req) |
||
| 36 | |||
| 37 | search_query = req.get_param('q', default=None) |
||
| 38 | if search_query is not None: |
||
| 39 | search_query = search_query.strip() |
||
| 40 | else: |
||
| 41 | search_query = '' |
||
| 42 | |||
| 43 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 44 | cursor = cnx.cursor() |
||
| 45 | |||
| 46 | svg_dict = dict() |
||
| 47 | query = (" SELECT id, name, uuid, source_code " |
||
| 48 | " FROM tbl_svgs ") |
||
| 49 | cursor.execute(query) |
||
| 50 | rows_svgs = cursor.fetchall() |
||
| 51 | if rows_svgs is not None and len(rows_svgs) > 0: |
||
| 52 | for row in rows_svgs: |
||
| 53 | svg_dict[row[0]] = {"id": row[0], |
||
| 54 | "name": row[1], |
||
| 55 | "uuid": row[2], |
||
| 56 | "source_code": row[3]} |
||
| 57 | |||
| 58 | query = (" SELECT id, name, uuid, " |
||
| 59 | " svg_id, description " |
||
| 60 | " FROM tbl_distribution_systems ") |
||
| 61 | |||
| 62 | params=[] |
||
| 63 | if search_query: |
||
| 64 | query += " WHERE name LIKE %s OR description LIKE %s " |
||
| 65 | params = [f'%{search_query}%', f'%{search_query}%'] |
||
| 66 | query += " ORDER BY id " |
||
| 67 | cursor.execute(query, params) |
||
| 68 | rows_distribution_systems = cursor.fetchall() |
||
| 69 | |||
| 70 | result = list() |
||
| 71 | if rows_distribution_systems is not None and len(rows_distribution_systems) > 0: |
||
| 72 | for row in rows_distribution_systems: |
||
| 73 | |||
| 74 | meta_result = {"id": row[0], |
||
| 75 | "name": row[1], |
||
| 76 | "uuid": row[2], |
||
| 77 | "svg": svg_dict.get(row[3], None), |
||
| 78 | "description": row[4]} |
||
| 79 | result.append(meta_result) |
||
| 80 | |||
| 81 | cursor.close() |
||
| 82 | cnx.close() |
||
| 83 | resp.text = json.dumps(result) |
||
| 84 | |||
| 85 | @staticmethod |
||
| 86 | @user_logger |
||
| 87 | def on_post(req, resp): |
||
| 88 | """Handles POST requests""" |
||
| 89 | admin_control(req) |
||
| 90 | try: |
||
| 91 | raw_json = req.stream.read().decode('utf-8') |
||
| 92 | except UnicodeDecodeError as ex: |
||
| 93 | print("Failed to decode request") |
||
| 94 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 95 | title='API.BAD_REQUEST', |
||
| 96 | description='API.INVALID_ENCODING') |
||
| 97 | except Exception as ex: |
||
| 98 | print("Unexpected error reading request stream") |
||
| 99 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 100 | title='API.BAD_REQUEST', |
||
| 101 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 102 | |||
| 103 | new_values = json.loads(raw_json) |
||
| 104 | |||
| 105 | if 'name' not in new_values['data'].keys() or \ |
||
| 106 | not isinstance(new_values['data']['name'], str) or \ |
||
| 107 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 108 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 109 | description='API.INVALID_DISTRIBUTION_SYSTEM_NAME') |
||
| 110 | name = str.strip(new_values['data']['name']) |
||
| 111 | |||
| 112 | if 'svg_id' not in new_values['data'].keys() or \ |
||
| 113 | not isinstance(new_values['data']['svg_id'], int) or \ |
||
| 114 | new_values['data']['svg_id'] <= 0: |
||
| 115 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 116 | description='API.INVALID_SVG_ID') |
||
| 117 | svg_id = new_values['data']['svg_id'] |
||
| 118 | |||
| 119 | if 'description' in new_values['data'].keys() and \ |
||
| 120 | new_values['data']['description'] is not None and \ |
||
| 121 | len(str(new_values['data']['description'])) > 0: |
||
| 122 | description = str.strip(new_values['data']['description']) |
||
| 123 | else: |
||
| 124 | description = None |
||
| 125 | |||
| 126 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 127 | cursor = cnx.cursor() |
||
| 128 | |||
| 129 | cursor.execute(" SELECT name " |
||
| 130 | " FROM tbl_distribution_systems " |
||
| 131 | " WHERE name = %s ", (name,)) |
||
| 132 | if cursor.fetchone() is not None: |
||
| 133 | cursor.close() |
||
| 134 | cnx.close() |
||
| 135 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 136 | description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE') |
||
| 137 | |||
| 138 | cursor.execute(" SELECT name " |
||
| 139 | " FROM tbl_svgs " |
||
| 140 | " WHERE id = %s ", |
||
| 141 | (svg_id,)) |
||
| 142 | row = cursor.fetchone() |
||
| 143 | if row is None: |
||
| 144 | cursor.close() |
||
| 145 | cnx.close() |
||
| 146 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 147 | description='API.SVG_NOT_FOUND') |
||
| 148 | |||
| 149 | add_values = (" INSERT INTO tbl_distribution_systems " |
||
| 150 | " (name, uuid, svg_id, description) " |
||
| 151 | " VALUES (%s, %s, %s, %s) ") |
||
| 152 | cursor.execute(add_values, (name, |
||
| 153 | str(uuid.uuid4()), |
||
| 154 | svg_id, |
||
| 155 | description)) |
||
| 156 | new_id = cursor.lastrowid |
||
| 157 | cnx.commit() |
||
| 158 | cursor.close() |
||
| 159 | cnx.close() |
||
| 160 | |||
| 161 | resp.status = falcon.HTTP_201 |
||
| 162 | resp.location = '/distributionsystems/' + str(new_id) |
||
| 163 | |||
| 164 | |||
| 165 | class DistributionSystemItem: |
||
| 166 | def __init__(self): |
||
| 167 | pass |
||
| 168 | |||
| 169 | @staticmethod |
||
| 170 | def on_options(req, resp, id_): |
||
| 171 | _ = req |
||
| 172 | resp.status = falcon.HTTP_200 |
||
| 173 | _ = id_ |
||
| 174 | |||
| 175 | @staticmethod |
||
| 176 | def on_get(req, resp, id_): |
||
| 177 | if 'API-KEY' not in req.headers or \ |
||
| 178 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 179 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 180 | access_control(req) |
||
| 181 | else: |
||
| 182 | api_key_control(req) |
||
| 183 | if not id_.isdigit() or int(id_) <= 0: |
||
| 184 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 185 | description='API.INVALID_DISTRIBUTION_SYSTEM_ID') |
||
| 186 | |||
| 187 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 188 | cursor = cnx.cursor() |
||
| 189 | |||
| 190 | svg_dict = dict() |
||
| 191 | query = (" SELECT id, name, uuid, source_code " |
||
| 192 | " FROM tbl_svgs ") |
||
| 193 | cursor.execute(query) |
||
| 194 | rows_svgs = cursor.fetchall() |
||
| 195 | if rows_svgs is not None and len(rows_svgs) > 0: |
||
| 196 | for row in rows_svgs: |
||
| 197 | svg_dict[row[0]] = {"id": row[0], |
||
| 198 | "name": row[1], |
||
| 199 | "uuid": row[2], |
||
| 200 | "source_code": row[3]} |
||
| 201 | |||
| 202 | query = (" SELECT id, name, uuid, " |
||
| 203 | " svg_id, description " |
||
| 204 | " FROM tbl_distribution_systems " |
||
| 205 | " WHERE id = %s ") |
||
| 206 | cursor.execute(query, (id_,)) |
||
| 207 | row = cursor.fetchone() |
||
| 208 | cursor.close() |
||
| 209 | cnx.close() |
||
| 210 | |||
| 211 | if row is None: |
||
| 212 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 213 | description='API.DISTRIBUTION_SYSTEM_NOT_FOUND') |
||
| 214 | else: |
||
| 215 | meta_result = {"id": row[0], |
||
| 216 | "name": row[1], |
||
| 217 | "uuid": row[2], |
||
| 218 | "svg": svg_dict.get(row[3], None), |
||
| 219 | "description": row[4]} |
||
| 220 | |||
| 221 | resp.text = json.dumps(meta_result) |
||
| 222 | |||
| 223 | @staticmethod |
||
| 224 | @user_logger |
||
| 225 | def on_delete(req, resp, id_): |
||
| 226 | admin_control(req) |
||
| 227 | if not id_.isdigit() or int(id_) <= 0: |
||
| 228 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 229 | description='API.INVALID_DISTRIBUTION_SYSTEM_ID') |
||
| 230 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 231 | cursor = cnx.cursor() |
||
| 232 | |||
| 233 | cursor.execute(" SELECT name " |
||
| 234 | " FROM tbl_distribution_systems " |
||
| 235 | " WHERE id = %s ", (id_,)) |
||
| 236 | if cursor.fetchone() is None: |
||
| 237 | cursor.close() |
||
| 238 | cnx.close() |
||
| 239 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 240 | description='API.DISTRIBUTION_SYSTEM_NOT_FOUND') |
||
| 241 | |||
| 242 | # check relation with spaces |
||
| 243 | cursor.execute(" SELECT id " |
||
| 244 | " FROM tbl_spaces_distribution_systems " |
||
| 245 | " WHERE distribution_system_id = %s ", (id_,)) |
||
| 246 | rows_spaces = cursor.fetchall() |
||
| 247 | if rows_spaces is not None and len(rows_spaces) > 0: |
||
| 248 | cursor.close() |
||
| 249 | cnx.close() |
||
| 250 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 251 | title='API.BAD_REQUEST', |
||
| 252 | description='API.THERE_IS_RELATION_WITH_SPACES') |
||
| 253 | |||
| 254 | cursor.execute(" DELETE FROM tbl_distribution_circuits_points WHERE distribution_circuit_id " |
||
| 255 | "IN (SELECT id FROM tbl_distribution_circuits WHERE distribution_system_id = %s) ", (id_,)) |
||
| 256 | cursor.execute(" DELETE FROM tbl_distribution_circuits WHERE distribution_system_id = %s ", (id_,)) |
||
| 257 | cursor.execute(" DELETE FROM tbl_distribution_systems WHERE id = %s ", (id_,)) |
||
| 258 | cnx.commit() |
||
| 259 | |||
| 260 | cursor.close() |
||
| 261 | cnx.close() |
||
| 262 | |||
| 263 | resp.status = falcon.HTTP_204 |
||
| 264 | |||
| 265 | @staticmethod |
||
| 266 | @user_logger |
||
| 267 | def on_put(req, resp, id_): |
||
| 268 | """Handles PUT requests""" |
||
| 269 | admin_control(req) |
||
| 270 | try: |
||
| 271 | raw_json = req.stream.read().decode('utf-8') |
||
| 272 | except UnicodeDecodeError as ex: |
||
| 273 | print("Failed to decode request") |
||
| 274 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 275 | title='API.BAD_REQUEST', |
||
| 276 | description='API.INVALID_ENCODING') |
||
| 277 | except Exception as ex: |
||
| 278 | print("Unexpected error reading request stream") |
||
| 279 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 280 | title='API.BAD_REQUEST', |
||
| 281 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 282 | |||
| 283 | if not id_.isdigit() or int(id_) <= 0: |
||
| 284 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 285 | description='API.INVALID_DISTRIBUTION_SYSTEM_ID') |
||
| 286 | |||
| 287 | new_values = json.loads(raw_json) |
||
| 288 | |||
| 289 | if 'name' not in new_values['data'].keys() or \ |
||
| 290 | not isinstance(new_values['data']['name'], str) or \ |
||
| 291 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 292 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 293 | description='API.INVALID_DISTRIBUTION_SYSTEM_NAME') |
||
| 294 | name = str.strip(new_values['data']['name']) |
||
| 295 | |||
| 296 | if 'svg_id' not in new_values['data'].keys() or \ |
||
| 297 | not isinstance(new_values['data']['svg_id'], int) or \ |
||
| 298 | new_values['data']['svg_id'] <= 0: |
||
| 299 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 300 | description='API.INVALID_SVG_ID') |
||
| 301 | svg_id = new_values['data']['svg_id'] |
||
| 302 | |||
| 303 | if 'description' in new_values['data'].keys() and \ |
||
| 304 | new_values['data']['description'] is not None and \ |
||
| 305 | len(str(new_values['data']['description'])) > 0: |
||
| 306 | description = str.strip(new_values['data']['description']) |
||
| 307 | else: |
||
| 308 | description = None |
||
| 309 | |||
| 310 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 311 | cursor = cnx.cursor() |
||
| 312 | |||
| 313 | cursor.execute(" SELECT name " |
||
| 314 | " FROM tbl_distribution_systems " |
||
| 315 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
| 316 | if cursor.fetchone() is not None: |
||
| 317 | cursor.close() |
||
| 318 | cnx.close() |
||
| 319 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 320 | description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE') |
||
| 321 | |||
| 322 | cursor.execute(" SELECT name " |
||
| 323 | " FROM tbl_svgs " |
||
| 324 | " WHERE id = %s ", |
||
| 325 | (new_values['data']['svg_id'],)) |
||
| 326 | row = cursor.fetchone() |
||
| 327 | if row is None: |
||
| 328 | cursor.close() |
||
| 329 | cnx.close() |
||
| 330 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 331 | description='API.SVG_NOT_FOUND') |
||
| 332 | |||
| 333 | update_row = (" UPDATE tbl_distribution_systems " |
||
| 334 | " SET name = %s, svg_id = %s, description = %s " |
||
| 335 | " WHERE id = %s ") |
||
| 336 | cursor.execute(update_row, (name, |
||
| 337 | svg_id, |
||
| 338 | description, |
||
| 339 | id_)) |
||
| 340 | cnx.commit() |
||
| 341 | |||
| 342 | cursor.close() |
||
| 343 | cnx.close() |
||
| 344 | |||
| 345 | resp.status = falcon.HTTP_200 |
||
| 346 | |||
| 347 | |||
| 348 | View Code Duplication | class DistributionSystemDistributionCircuitCollection: |
|
|
|
|||
| 349 | def __init__(self): |
||
| 350 | pass |
||
| 351 | |||
| 352 | @staticmethod |
||
| 353 | def on_options(req, resp, id_): |
||
| 354 | _ = req |
||
| 355 | resp.status = falcon.HTTP_200 |
||
| 356 | _ = id_ |
||
| 357 | |||
| 358 | @staticmethod |
||
| 359 | def on_get(req, resp, id_): |
||
| 360 | if 'API-KEY' not in req.headers or \ |
||
| 361 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 362 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 363 | access_control(req) |
||
| 364 | else: |
||
| 365 | api_key_control(req) |
||
| 366 | if not id_.isdigit() or int(id_) <= 0: |
||
| 367 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 368 | description='API.INVALID_DISTRIBUTION_SYSTEM_ID') |
||
| 369 | |||
| 370 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 371 | cursor = cnx.cursor() |
||
| 372 | |||
| 373 | cursor.execute(" SELECT name " |
||
| 374 | " FROM tbl_distribution_systems " |
||
| 375 | " WHERE id = %s ", (id_,)) |
||
| 376 | if cursor.fetchone() is None: |
||
| 377 | cursor.close() |
||
| 378 | cnx.close() |
||
| 379 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 380 | description='API.DISTRIBUTION_SYSTEM_NOT_FOUND') |
||
| 381 | |||
| 382 | query = (" SELECT id, name, uuid, " |
||
| 383 | " distribution_room, switchgear, peak_load, peak_current, customers, meters " |
||
| 384 | " FROM tbl_distribution_circuits " |
||
| 385 | " WHERE distribution_system_id = %s " |
||
| 386 | " ORDER BY name ") |
||
| 387 | cursor.execute(query, (id_,)) |
||
| 388 | rows = cursor.fetchall() |
||
| 389 | |||
| 390 | result = list() |
||
| 391 | if rows is not None and len(rows) > 0: |
||
| 392 | for row in rows: |
||
| 393 | meta_result = {"id": row[0], "name": row[1], "uuid": row[2], |
||
| 394 | "distribution_room": row[3], "switchgear": row[4], |
||
| 395 | "peak_load": row[5], "peak_current": row[6], |
||
| 396 | "customers": row[7], "meters": row[8]} |
||
| 397 | result.append(meta_result) |
||
| 398 | |||
| 399 | resp.text = json.dumps(result) |
||
| 400 | |||
| 401 | |||
| 402 | class DistributionSystemExport: |
||
| 403 | def __init__(self): |
||
| 404 | pass |
||
| 405 | |||
| 406 | @staticmethod |
||
| 407 | def on_options(req, resp, id_): |
||
| 408 | _ = req |
||
| 409 | resp.status = falcon.HTTP_200 |
||
| 410 | _ = id_ |
||
| 411 | |||
| 412 | @staticmethod |
||
| 413 | def on_get(req, resp, id_): |
||
| 414 | if 'API-KEY' not in req.headers or \ |
||
| 415 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 416 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 417 | access_control(req) |
||
| 418 | else: |
||
| 419 | api_key_control(req) |
||
| 420 | if not id_.isdigit() or int(id_) <= 0: |
||
| 421 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 422 | description='API.INVALID_DISTRIBUTION_SYSTEM_ID') |
||
| 423 | |||
| 424 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 425 | cursor = cnx.cursor() |
||
| 426 | |||
| 427 | query = (" SELECT id, name, uuid " |
||
| 428 | " FROM tbl_svgs ") |
||
| 429 | cursor.execute(query) |
||
| 430 | rows_svgs = cursor.fetchall() |
||
| 431 | |||
| 432 | svg_dict = dict() |
||
| 433 | if rows_svgs is not None and len(rows_svgs) > 0: |
||
| 434 | for row in rows_svgs: |
||
| 435 | svg_dict[row[0]] = {"id": row[0], |
||
| 436 | "name": row[1], |
||
| 437 | "uuid": row[2]} |
||
| 438 | |||
| 439 | query = (" SELECT id, name, uuid, " |
||
| 440 | " svg_id, description " |
||
| 441 | " FROM tbl_distribution_systems " |
||
| 442 | " WHERE id = %s ") |
||
| 443 | cursor.execute(query, (id_,)) |
||
| 444 | row = cursor.fetchone() |
||
| 445 | |||
| 446 | if row is None: |
||
| 447 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 448 | description='API.DISTRIBUTION_SYSTEM_NOT_FOUND') |
||
| 449 | else: |
||
| 450 | meta_result = {"id": row[0], |
||
| 451 | "name": row[1], |
||
| 452 | "uuid": row[2], |
||
| 453 | "svg": svg_dict.get(row[3], None), |
||
| 454 | "description": row[4], |
||
| 455 | "circuits": None} |
||
| 456 | query = (" SELECT id, name, uuid, " |
||
| 457 | " distribution_room, switchgear, peak_load, peak_current, customers, meters " |
||
| 458 | " FROM tbl_distribution_circuits " |
||
| 459 | " WHERE distribution_system_id = %s " |
||
| 460 | " ORDER BY name ") |
||
| 461 | cursor.execute(query, (id_,)) |
||
| 462 | rows = cursor.fetchall() |
||
| 463 | |||
| 464 | result = list() |
||
| 465 | View Code Duplication | if rows is not None and len(rows) > 0: |
|
| 466 | for row in rows: |
||
| 467 | circuit_result = {"id": row[0], "name": row[1], "uuid": row[2], |
||
| 468 | "distribution_room": row[3], "switchgear": row[4], |
||
| 469 | "peak_load": row[5], "peak_current": row[6], |
||
| 470 | "customers": row[7], "meters": row[8], |
||
| 471 | "points": None} |
||
| 472 | query = (" SELECT p.id AS point_id, p.name AS point_name, " |
||
| 473 | " dc.id AS distribution_circuit_id, dc.name AS distribution_circuit_name, " |
||
| 474 | " dc.uuid AS distribution_circuit_uuid " |
||
| 475 | " FROM tbl_points p, tbl_distribution_circuits_points dcp, tbl_distribution_circuits dc " |
||
| 476 | " WHERE dcp.distribution_circuit_id = %s AND p.id = dcp.point_id " |
||
| 477 | " AND dcp.distribution_circuit_id = dc.id " |
||
| 478 | " ORDER BY p.name ") |
||
| 479 | cursor.execute(query, (circuit_result['id'],)) |
||
| 480 | rows = cursor.fetchall() |
||
| 481 | |||
| 482 | points = list() |
||
| 483 | if rows is not None and len(rows) > 0: |
||
| 484 | for point_row in rows: |
||
| 485 | point_result = {"id": point_row[0], "name": point_row[1]} |
||
| 486 | points.append(point_result) |
||
| 487 | circuit_result['points'] = points |
||
| 488 | |||
| 489 | result.append(circuit_result) |
||
| 490 | meta_result['circuits'] = result |
||
| 491 | |||
| 492 | cursor.close() |
||
| 493 | cnx.close() |
||
| 494 | resp.text = json.dumps(meta_result) |
||
| 495 | |||
| 496 | |||
| 497 | class DistributionSystemImport: |
||
| 498 | def __init__(self): |
||
| 499 | pass |
||
| 500 | |||
| 501 | @staticmethod |
||
| 502 | def on_options(req, resp): |
||
| 503 | _ = req |
||
| 504 | resp.status = falcon.HTTP_200 |
||
| 505 | |||
| 506 | @staticmethod |
||
| 507 | @user_logger |
||
| 508 | def on_post(req, resp): |
||
| 509 | """Handles POST requests""" |
||
| 510 | admin_control(req) |
||
| 511 | try: |
||
| 512 | raw_json = req.stream.read().decode('utf-8') |
||
| 513 | except UnicodeDecodeError as ex: |
||
| 514 | print("Failed to decode request") |
||
| 515 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 516 | title='API.BAD_REQUEST', |
||
| 517 | description='API.INVALID_ENCODING') |
||
| 518 | except Exception as ex: |
||
| 519 | print("Unexpected error reading request stream") |
||
| 520 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 521 | title='API.BAD_REQUEST', |
||
| 522 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 523 | |||
| 524 | new_values = json.loads(raw_json) |
||
| 525 | |||
| 526 | if 'name' not in new_values.keys() or \ |
||
| 527 | not isinstance(new_values['name'], str) or \ |
||
| 528 | len(str.strip(new_values['name'])) == 0: |
||
| 529 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 530 | description='API.INVALID_DISTRIBUTION_SYSTEM_NAME') |
||
| 531 | name = str.strip(new_values['name']) |
||
| 532 | |||
| 533 | if 'svg' not in new_values.keys() or \ |
||
| 534 | 'id' not in new_values['svg'].keys() or \ |
||
| 535 | not isinstance(new_values['svg']['id'], int) or \ |
||
| 536 | new_values['svg']['id'] <= 0: |
||
| 537 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 538 | description='API.INVALID_SVG_ID') |
||
| 539 | svg_id = new_values['svg']['id'] |
||
| 540 | |||
| 541 | if 'description' in new_values.keys() and \ |
||
| 542 | new_values['description'] is not None and \ |
||
| 543 | len(str(new_values['description'])) > 0: |
||
| 544 | description = str.strip(new_values['description']) |
||
| 545 | else: |
||
| 546 | description = None |
||
| 547 | |||
| 548 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 549 | cursor = cnx.cursor() |
||
| 550 | |||
| 551 | cursor.execute(" SELECT name " |
||
| 552 | " FROM tbl_distribution_systems " |
||
| 553 | " WHERE name = %s ", (name,)) |
||
| 554 | if cursor.fetchone() is not None: |
||
| 555 | cursor.close() |
||
| 556 | cnx.close() |
||
| 557 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 558 | description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE') |
||
| 559 | |||
| 560 | cursor.execute(" SELECT name " |
||
| 561 | " FROM tbl_svgs " |
||
| 562 | " WHERE id = %s ", |
||
| 563 | (svg_id,)) |
||
| 564 | row = cursor.fetchone() |
||
| 565 | if row is None: |
||
| 566 | cursor.close() |
||
| 567 | cnx.close() |
||
| 568 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 569 | description='API.SVG_NOT_FOUND') |
||
| 570 | |||
| 571 | add_values = (" INSERT INTO tbl_distribution_systems " |
||
| 572 | " (name, uuid, svg_id, description) " |
||
| 573 | " VALUES (%s, %s, %s, %s) ") |
||
| 574 | cursor.execute(add_values, (name, |
||
| 575 | str(uuid.uuid4()), |
||
| 576 | svg_id, |
||
| 577 | description)) |
||
| 578 | new_id = cursor.lastrowid |
||
| 579 | View Code Duplication | if new_values['circuits'] is not None and len(new_values['circuits']) > 0: |
|
| 580 | for circuit in new_values['circuits']: |
||
| 581 | add_values = (" INSERT INTO tbl_distribution_circuits " |
||
| 582 | " (name, uuid, distribution_system_id," |
||
| 583 | " distribution_room, switchgear, peak_load, peak_current, customers, meters) " |
||
| 584 | " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ") |
||
| 585 | cursor.execute(add_values, (circuit['name'], |
||
| 586 | str(uuid.uuid4()), |
||
| 587 | new_id, |
||
| 588 | circuit['distribution_room'], |
||
| 589 | circuit['switchgear'], |
||
| 590 | circuit['peak_load'], |
||
| 591 | circuit['peak_current'], |
||
| 592 | circuit['customers'], |
||
| 593 | circuit['meters'])) |
||
| 594 | circuit_id = cursor.lastrowid |
||
| 595 | if circuit['points'] is not None and len(circuit['points']) > 0: |
||
| 596 | for point in circuit['points']: |
||
| 597 | cursor.execute(" SELECT name " |
||
| 598 | " FROM tbl_points " |
||
| 599 | " WHERE id = %s ", (point['id'],)) |
||
| 600 | if cursor.fetchone() is None: |
||
| 601 | cursor.close() |
||
| 602 | cnx.close() |
||
| 603 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 604 | description='API.POINT_NOT_FOUND') |
||
| 605 | |||
| 606 | query = (" SELECT id " |
||
| 607 | " FROM tbl_distribution_circuits_points " |
||
| 608 | " WHERE distribution_circuit_id = %s AND point_id = %s") |
||
| 609 | cursor.execute(query, (circuit_id, point['id'],)) |
||
| 610 | if cursor.fetchone() is not None: |
||
| 611 | cursor.close() |
||
| 612 | cnx.close() |
||
| 613 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR', |
||
| 614 | description='API.DISTRIBUTION_CIRCUIT_POINT_RELATION_EXISTS') |
||
| 615 | |||
| 616 | add_row = (" INSERT INTO tbl_distribution_circuits_points (distribution_circuit_id, point_id) " |
||
| 617 | " VALUES (%s, %s) ") |
||
| 618 | cursor.execute(add_row, (circuit_id, point['id'],)) |
||
| 619 | |||
| 620 | cnx.commit() |
||
| 621 | cursor.close() |
||
| 622 | cnx.close() |
||
| 623 | |||
| 624 | resp.status = falcon.HTTP_201 |
||
| 625 | resp.location = '/distributionsystems/' + str(new_id) |
||
| 626 | |||
| 627 | |||
| 628 | class DistributionSystemClone: |
||
| 629 | def __init__(self): |
||
| 630 | pass |
||
| 631 | |||
| 632 | @staticmethod |
||
| 633 | def on_options(req, resp, id_): |
||
| 634 | _ = req |
||
| 635 | resp.status = falcon.HTTP_200 |
||
| 636 | _ = id_ |
||
| 637 | |||
| 638 | @staticmethod |
||
| 639 | @user_logger |
||
| 640 | def on_post(req, resp, id_): |
||
| 641 | admin_control(req) |
||
| 642 | if not id_.isdigit() or int(id_) <= 0: |
||
| 643 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 644 | description='API.INVALID_DISTRIBUTION_SYSTEM_ID') |
||
| 645 | |||
| 646 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 647 | cursor = cnx.cursor() |
||
| 648 | |||
| 649 | query = (" SELECT id, name, uuid, " |
||
| 650 | " svg_id, description " |
||
| 651 | " FROM tbl_distribution_systems " |
||
| 652 | " WHERE id = %s ") |
||
| 653 | cursor.execute(query, (id_,)) |
||
| 654 | row = cursor.fetchone() |
||
| 655 | |||
| 656 | if row is None: |
||
| 657 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 658 | description='API.DISTRIBUTION_SYSTEM_NOT_FOUND') |
||
| 659 | else: |
||
| 660 | meta_result = {"id": row[0], |
||
| 661 | "name": row[1], |
||
| 662 | "uuid": row[2], |
||
| 663 | "svg_id": row[3], |
||
| 664 | "description": row[4], |
||
| 665 | "circuits": None} |
||
| 666 | query = (" SELECT id, name, uuid, " |
||
| 667 | " distribution_room, switchgear, peak_load, peak_current, customers, meters " |
||
| 668 | " FROM tbl_distribution_circuits " |
||
| 669 | " WHERE distribution_system_id = %s " |
||
| 670 | " ORDER BY name ") |
||
| 671 | cursor.execute(query, (id_,)) |
||
| 672 | rows = cursor.fetchall() |
||
| 673 | |||
| 674 | result = list() |
||
| 675 | View Code Duplication | if rows is not None and len(rows) > 0: |
|
| 676 | for row in rows: |
||
| 677 | circuit_result = {"id": row[0], "name": row[1], "uuid": row[2], |
||
| 678 | "distribution_room": row[3], "switchgear": row[4], |
||
| 679 | "peak_load": row[5], "peak_current": row[6], |
||
| 680 | "customers": row[7], "meters": row[8], |
||
| 681 | "points": None} |
||
| 682 | query = (" SELECT p.id AS point_id, p.name AS point_name, p.address AS point_address, " |
||
| 683 | " dc.id AS distribution_circuit_id, dc.name AS distribution_circuit_name, " |
||
| 684 | " dc.uuid AS distribution_circuit_uuid " |
||
| 685 | " FROM tbl_points p, tbl_distribution_circuits_points dcp, tbl_distribution_circuits dc " |
||
| 686 | " WHERE dcp.distribution_circuit_id = %s AND p.id = dcp.point_id " |
||
| 687 | " AND dcp.distribution_circuit_id = dc.id " |
||
| 688 | " ORDER BY p.name ") |
||
| 689 | cursor.execute(query, (circuit_result['id'],)) |
||
| 690 | rows = cursor.fetchall() |
||
| 691 | |||
| 692 | points = list() |
||
| 693 | if rows is not None and len(rows) > 0: |
||
| 694 | for point_row in rows: |
||
| 695 | point_result = {"id": point_row[0], "name": point_row[1], "address": point_row[2]} |
||
| 696 | points.append(point_result) |
||
| 697 | circuit_result['points'] = points |
||
| 698 | |||
| 699 | result.append(circuit_result) |
||
| 700 | meta_result['circuits'] = result |
||
| 701 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
| 702 | if config.utc_offset[0] == '-': |
||
| 703 | timezone_offset = -timezone_offset |
||
| 704 | new_name = (str.strip(meta_result['name']) + |
||
| 705 | (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds')) |
||
| 706 | add_values = (" INSERT INTO tbl_distribution_systems " |
||
| 707 | " (name, uuid, svg_id, description) " |
||
| 708 | " VALUES (%s, %s, %s, %s) ") |
||
| 709 | cursor.execute(add_values, (new_name, |
||
| 710 | str(uuid.uuid4()), |
||
| 711 | meta_result['svg_id'], |
||
| 712 | meta_result['description'])) |
||
| 713 | new_id = cursor.lastrowid |
||
| 714 | View Code Duplication | if meta_result['circuits'] is not None and len(meta_result['circuits']) > 0: |
|
| 715 | for circuit in meta_result['circuits']: |
||
| 716 | add_values = (" INSERT INTO tbl_distribution_circuits " |
||
| 717 | " (name, uuid, distribution_system_id," |
||
| 718 | " distribution_room, switchgear, peak_load, peak_current, customers, meters) " |
||
| 719 | " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ") |
||
| 720 | cursor.execute(add_values, (circuit['name'], |
||
| 721 | str(uuid.uuid4()), |
||
| 722 | new_id, |
||
| 723 | circuit['distribution_room'], |
||
| 724 | circuit['switchgear'], |
||
| 725 | circuit['peak_load'], |
||
| 726 | circuit['peak_current'], |
||
| 727 | circuit['customers'], |
||
| 728 | circuit['meters'])) |
||
| 729 | circuit_id = cursor.lastrowid |
||
| 730 | if circuit['points'] is not None and len(circuit['points']) > 0: |
||
| 731 | for point in circuit['points']: |
||
| 732 | cursor.execute(" SELECT name " |
||
| 733 | " FROM tbl_points " |
||
| 734 | " WHERE id = %s ", (point['id'],)) |
||
| 735 | if cursor.fetchone() is None: |
||
| 736 | cursor.close() |
||
| 737 | cnx.close() |
||
| 738 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 739 | description='API.POINT_NOT_FOUND') |
||
| 740 | |||
| 741 | query = (" SELECT id " |
||
| 742 | " FROM tbl_distribution_circuits_points " |
||
| 743 | " WHERE distribution_circuit_id = %s AND point_id = %s") |
||
| 744 | cursor.execute(query, (circuit_id, point['id'],)) |
||
| 745 | if cursor.fetchone() is not None: |
||
| 746 | cursor.close() |
||
| 747 | cnx.close() |
||
| 748 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR', |
||
| 749 | description='API.DISTRIBUTION_CIRCUIT_POINT_RELATION_EXISTS') |
||
| 750 | |||
| 751 | add_row = ( |
||
| 752 | " INSERT INTO tbl_distribution_circuits_points (distribution_circuit_id, point_id) " |
||
| 753 | " VALUES (%s, %s) ") |
||
| 754 | cursor.execute(add_row, (circuit_id, point['id'],)) |
||
| 755 | cnx.commit() |
||
| 756 | cursor.close() |
||
| 757 | cnx.close() |
||
| 758 | |||
| 759 | resp.status = falcon.HTTP_201 |
||
| 760 | resp.location = '/distributionsystems/' + str(new_id) |
||
| 761 |