| Total Complexity | 79 |
| Total Lines | 434 |
| Duplicated Lines | 7.83 % |
| 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.contact 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 re |
||
| 2 | import uuid |
||
| 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 ContactCollection: |
||
| 11 | """ |
||
| 12 | Contact Collection Resource |
||
| 13 | |||
| 14 | This class handles CRUD operations for contact collection. |
||
| 15 | It provides endpoints for listing all contacts and creating new contacts. |
||
| 16 | Contacts represent individuals or organizations in the energy management system. |
||
| 17 | """ |
||
| 18 | def __init__(self): |
||
| 19 | """Initialize ContactCollection""" |
||
| 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 | search_query = req.get_param('q', default=None) |
||
| 37 | if search_query is not None: |
||
| 38 | search_query = search_query.strip() |
||
| 39 | else: |
||
| 40 | search_query = '' |
||
| 41 | |||
| 42 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 43 | cursor = cnx.cursor() |
||
| 44 | |||
| 45 | query = (" SELECT id, name, uuid, " |
||
| 46 | " email, phone, description " |
||
| 47 | " FROM tbl_contacts " ) |
||
| 48 | |||
| 49 | params=[] |
||
| 50 | if search_query: |
||
| 51 | query += " WHERE name LIKE %s OR description LIKE %s " |
||
| 52 | params = [f'%{search_query}%', f'%{search_query}%'] |
||
| 53 | query += " ORDER BY name " |
||
| 54 | |||
| 55 | cursor.execute(query,params) |
||
| 56 | rows = cursor.fetchall() |
||
| 57 | cursor.close() |
||
| 58 | cnx.close() |
||
| 59 | |||
| 60 | result = list() |
||
| 61 | if rows is not None and len(rows) > 0: |
||
| 62 | for row in rows: |
||
| 63 | meta_result = {"id": row[0], |
||
| 64 | "name": row[1], |
||
| 65 | "uuid": row[2], |
||
| 66 | "email": row[3], |
||
| 67 | "phone": row[4], |
||
| 68 | "description": row[5]} |
||
| 69 | result.append(meta_result) |
||
| 70 | |||
| 71 | resp.text = json.dumps(result) |
||
| 72 | |||
| 73 | @staticmethod |
||
| 74 | @user_logger |
||
| 75 | def on_post(req, resp): |
||
| 76 | """Handles POST requests""" |
||
| 77 | admin_control(req) |
||
| 78 | try: |
||
| 79 | raw_json = req.stream.read().decode('utf-8') |
||
| 80 | except Exception as ex: |
||
| 81 | print(ex) |
||
| 82 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 83 | title='API.BAD_REQUEST', |
||
| 84 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 85 | |||
| 86 | new_values = json.loads(raw_json) |
||
| 87 | |||
| 88 | if 'name' not in new_values['data'].keys() or \ |
||
| 89 | not isinstance(new_values['data']['name'], str) or \ |
||
| 90 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 91 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 92 | description='API.INVALID_USER_NAME') |
||
| 93 | name = str.strip(new_values['data']['name']) |
||
| 94 | |||
| 95 | if 'email' not in new_values['data'].keys() or \ |
||
| 96 | not isinstance(new_values['data']['email'], str) or \ |
||
| 97 | len(str.strip(new_values['data']['email'])) == 0: |
||
| 98 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 99 | description='API.INVALID_EMAIL') |
||
| 100 | email = str.lower(str.strip(new_values['data']['email'])) |
||
| 101 | |||
| 102 | match = re.match(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) |
||
| 103 | if match is None: |
||
| 104 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 105 | description='API.INVALID_EMAIL') |
||
| 106 | |||
| 107 | if 'phone' not in new_values['data'].keys() or \ |
||
| 108 | not isinstance(new_values['data']['phone'], str) or \ |
||
| 109 | len(str.strip(new_values['data']['phone'])) == 0: |
||
| 110 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 111 | description='API.INVALID_USER_PHONE') |
||
| 112 | phone = str.strip(new_values['data']['phone']) |
||
| 113 | |||
| 114 | if 'description' in new_values['data'].keys() and \ |
||
| 115 | new_values['data']['description'] is not None and \ |
||
| 116 | len(str(new_values['data']['description'])) > 0: |
||
| 117 | description = str.strip(new_values['data']['description']) |
||
| 118 | else: |
||
| 119 | description = None |
||
| 120 | |||
| 121 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 122 | cursor = cnx.cursor() |
||
| 123 | |||
| 124 | cursor.execute(" SELECT name " |
||
| 125 | " FROM tbl_contacts " |
||
| 126 | " WHERE name = %s ", (name,)) |
||
| 127 | if cursor.fetchone() is not None: |
||
| 128 | cursor.close() |
||
| 129 | cnx.close() |
||
| 130 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 131 | description='API.CONTACT_NAME_IS_ALREADY_IN_USE') |
||
| 132 | |||
| 133 | add_row = (" INSERT INTO tbl_contacts " |
||
| 134 | " (name, uuid, email, phone, description) " |
||
| 135 | " VALUES (%s, %s, %s, %s, %s) ") |
||
| 136 | |||
| 137 | cursor.execute(add_row, (name, |
||
| 138 | str(uuid.uuid4()), |
||
| 139 | email, |
||
| 140 | phone, |
||
| 141 | description)) |
||
| 142 | new_id = cursor.lastrowid |
||
| 143 | cnx.commit() |
||
| 144 | cursor.close() |
||
| 145 | cnx.close() |
||
| 146 | |||
| 147 | resp.status = falcon.HTTP_201 |
||
| 148 | resp.location = '/contacts/' + str(new_id) |
||
| 149 | |||
| 150 | |||
| 151 | class ContactItem: |
||
| 152 | def __init__(self): |
||
| 153 | pass |
||
| 154 | |||
| 155 | @staticmethod |
||
| 156 | def on_options(req, resp, id_): |
||
| 157 | _ = id_ |
||
| 158 | _ = req |
||
| 159 | resp.status = falcon.HTTP_200 |
||
| 160 | |||
| 161 | View Code Duplication | @staticmethod |
|
|
|
|||
| 162 | def on_get(req, resp, id_): |
||
| 163 | if 'API-KEY' not in req.headers or \ |
||
| 164 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 165 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 166 | access_control(req) |
||
| 167 | else: |
||
| 168 | api_key_control(req) |
||
| 169 | if not id_.isdigit() or int(id_) <= 0: |
||
| 170 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 171 | description='API.INVALID_CONTACT_ID') |
||
| 172 | |||
| 173 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 174 | cursor = cnx.cursor() |
||
| 175 | |||
| 176 | query = (" SELECT id, name, uuid, email, phone, description " |
||
| 177 | " FROM tbl_contacts " |
||
| 178 | " WHERE id = %s ") |
||
| 179 | cursor.execute(query, (id_,)) |
||
| 180 | row = cursor.fetchone() |
||
| 181 | cursor.close() |
||
| 182 | cnx.close() |
||
| 183 | |||
| 184 | if row is None: |
||
| 185 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 186 | description='API.CONTACT_NOT_FOUND') |
||
| 187 | |||
| 188 | result = {"id": row[0], |
||
| 189 | "name": row[1], |
||
| 190 | "uuid": row[2], |
||
| 191 | "email": row[3], |
||
| 192 | "phone": row[4], |
||
| 193 | "description": row[5]} |
||
| 194 | resp.text = json.dumps(result) |
||
| 195 | |||
| 196 | @staticmethod |
||
| 197 | @user_logger |
||
| 198 | def on_delete(req, resp, id_): |
||
| 199 | admin_control(req) |
||
| 200 | if not id_.isdigit() or int(id_) <= 0: |
||
| 201 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 202 | description='API.INVALID_CONTACT_ID') |
||
| 203 | |||
| 204 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 205 | cursor = cnx.cursor() |
||
| 206 | |||
| 207 | cursor.execute(" SELECT name " |
||
| 208 | " FROM tbl_contacts " |
||
| 209 | " WHERE id = %s ", (id_,)) |
||
| 210 | if cursor.fetchone() is None: |
||
| 211 | cursor.close() |
||
| 212 | cnx.close() |
||
| 213 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 214 | description='API.CONTACT_NOT_FOUND') |
||
| 215 | |||
| 216 | # check relation with shopfloors |
||
| 217 | cursor.execute(" SELECT id " |
||
| 218 | " FROM tbl_shopfloors " |
||
| 219 | " WHERE contact_id = %s ", (id_,)) |
||
| 220 | rows_shopfloors = cursor.fetchall() |
||
| 221 | if rows_shopfloors is not None and len(rows_shopfloors) > 0: |
||
| 222 | cursor.close() |
||
| 223 | cnx.close() |
||
| 224 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 225 | title='API.BAD_REQUEST', |
||
| 226 | description='API.THERE_IS_RELATION_WITH_SHOPFLOORS') |
||
| 227 | |||
| 228 | # check relation with spaces |
||
| 229 | cursor.execute(" SELECT id " |
||
| 230 | " FROM tbl_spaces " |
||
| 231 | " WHERE contact_id = %s ", (id_,)) |
||
| 232 | rows_spaces = cursor.fetchall() |
||
| 233 | if rows_spaces is not None and len(rows_spaces) > 0: |
||
| 234 | cursor.close() |
||
| 235 | cnx.close() |
||
| 236 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 237 | title='API.BAD_REQUEST', |
||
| 238 | description='API.THERE_IS_RELATION_WITH_SPACES') |
||
| 239 | |||
| 240 | # check relation with stores |
||
| 241 | cursor.execute(" SELECT id " |
||
| 242 | " FROM tbl_stores " |
||
| 243 | " WHERE contact_id = %s ", (id_,)) |
||
| 244 | rows_stores = cursor.fetchall() |
||
| 245 | if rows_stores is not None and len(rows_stores) > 0: |
||
| 246 | cursor.close() |
||
| 247 | cnx.close() |
||
| 248 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 249 | title='API.BAD_REQUEST', |
||
| 250 | description='API.THERE_IS_RELATION_WITH_STORES') |
||
| 251 | |||
| 252 | # check relation with tenants |
||
| 253 | cursor.execute(" SELECT id " |
||
| 254 | " FROM tbl_tenants " |
||
| 255 | " WHERE contact_id = %s ", (id_,)) |
||
| 256 | rows_tenants = cursor.fetchall() |
||
| 257 | if rows_tenants is not None and len(rows_tenants) > 0: |
||
| 258 | cursor.close() |
||
| 259 | cnx.close() |
||
| 260 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 261 | title='API.BAD_REQUEST', |
||
| 262 | description='API.THERE_IS_RELATION_WITH_TENANTS') |
||
| 263 | |||
| 264 | # check relation with charging_stations |
||
| 265 | cursor.execute(" SELECT id " |
||
| 266 | " FROM tbl_charging_stations " |
||
| 267 | " WHERE contact_id = %s ", (id_,)) |
||
| 268 | rows_charging_stations = cursor.fetchall() |
||
| 269 | if rows_charging_stations is not None and len(rows_charging_stations) > 0: |
||
| 270 | cursor.close() |
||
| 271 | cnx.close() |
||
| 272 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 273 | title='API.BAD_REQUEST', |
||
| 274 | description='API.THERE_IS_RELATION_WITH_CHARGING_STATIONS') |
||
| 275 | |||
| 276 | # check relation with energy_storage_containers |
||
| 277 | cursor.execute(" SELECT id " |
||
| 278 | " FROM tbl_energy_storage_containers " |
||
| 279 | " WHERE contact_id = %s ", (id_,)) |
||
| 280 | rows_energy_storage_containers = cursor.fetchall() |
||
| 281 | if rows_energy_storage_containers is not None and len(rows_energy_storage_containers) > 0: |
||
| 282 | cursor.close() |
||
| 283 | cnx.close() |
||
| 284 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 285 | title='API.BAD_REQUEST', |
||
| 286 | description='API.THERE_IS_RELATION_WITH_ENERGY_STORAGE_CONTAINERS') |
||
| 287 | |||
| 288 | |||
| 289 | # check relation with energy_storage_power_stations |
||
| 290 | cursor.execute(" SELECT id " |
||
| 291 | " FROM tbl_energy_storage_power_stations " |
||
| 292 | " WHERE contact_id = %s ", (id_,)) |
||
| 293 | rows_energy_storage_power_stations = cursor.fetchall() |
||
| 294 | if rows_energy_storage_power_stations is not None and len(rows_energy_storage_power_stations) > 0: |
||
| 295 | cursor.close() |
||
| 296 | cnx.close() |
||
| 297 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 298 | title='API.BAD_REQUEST', |
||
| 299 | description='API.THERE_IS_RELATION_WITH_ENERGY_STORAGE_POWER_STATIONS') |
||
| 300 | |||
| 301 | # check relation with microgrids |
||
| 302 | cursor.execute(" SELECT id " |
||
| 303 | " FROM tbl_microgrids " |
||
| 304 | " WHERE contact_id = %s ", (id_,)) |
||
| 305 | rows_microgrids = cursor.fetchall() |
||
| 306 | if rows_microgrids is not None and len(rows_microgrids) > 0: |
||
| 307 | cursor.close() |
||
| 308 | cnx.close() |
||
| 309 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 310 | title='API.BAD_REQUEST', |
||
| 311 | description='API.THERE_IS_RELATION_WITH_MICROGRIDS') |
||
| 312 | |||
| 313 | # check relation with photovoltaic_power_stations |
||
| 314 | cursor.execute(" SELECT id " |
||
| 315 | " FROM tbl_photovoltaic_power_stations " |
||
| 316 | " WHERE contact_id = %s ", (id_,)) |
||
| 317 | rows_photovoltaic_power_stations = cursor.fetchall() |
||
| 318 | if rows_photovoltaic_power_stations is not None and len(rows_photovoltaic_power_stations) > 0: |
||
| 319 | cursor.close() |
||
| 320 | cnx.close() |
||
| 321 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 322 | title='API.BAD_REQUEST', |
||
| 323 | description='API.THERE_IS_RELATION_WITH_PHOTOVOLTAIC_POWER_STATIONS') |
||
| 324 | |||
| 325 | #check relation with wind_farms |
||
| 326 | cursor.execute(" SELECT id " |
||
| 327 | " FROM tbl_wind_farms " |
||
| 328 | " WHERE contact_id = %s ", (id_,)) |
||
| 329 | rows_wind_farms = cursor.fetchall() |
||
| 330 | if rows_wind_farms is not None and len(rows_wind_farms) > 0: |
||
| 331 | cursor.close() |
||
| 332 | cnx.close() |
||
| 333 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 334 | title='API.BAD_REQUEST', |
||
| 335 | description='API.THERE_IS_RELATION_WITH_WIND_FARMS') |
||
| 336 | |||
| 337 | |||
| 338 | cursor.execute(" DELETE FROM tbl_contacts WHERE id = %s ", (id_,)) |
||
| 339 | cnx.commit() |
||
| 340 | |||
| 341 | cursor.close() |
||
| 342 | cnx.close() |
||
| 343 | |||
| 344 | resp.status = falcon.HTTP_204 |
||
| 345 | |||
| 346 | @staticmethod |
||
| 347 | @user_logger |
||
| 348 | def on_put(req, resp, id_): |
||
| 349 | """Handles PUT requests""" |
||
| 350 | admin_control(req) |
||
| 351 | try: |
||
| 352 | raw_json = req.stream.read().decode('utf-8') |
||
| 353 | except Exception as ex: |
||
| 354 | print(ex) |
||
| 355 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 356 | title='API.BAD_REQUEST', |
||
| 357 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 358 | |||
| 359 | if not id_.isdigit() or int(id_) <= 0: |
||
| 360 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 361 | description='API.INVALID_CONTACT_ID') |
||
| 362 | |||
| 363 | new_values = json.loads(raw_json) |
||
| 364 | |||
| 365 | if 'name' not in new_values['data'].keys() or \ |
||
| 366 | not isinstance(new_values['data']['name'], str) or \ |
||
| 367 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 368 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 369 | description='API.INVALID_CONTACT_NAME') |
||
| 370 | name = str.strip(new_values['data']['name']) |
||
| 371 | |||
| 372 | if 'email' not in new_values['data'].keys() or \ |
||
| 373 | not isinstance(new_values['data']['email'], str) or \ |
||
| 374 | len(str.strip(new_values['data']['email'])) == 0: |
||
| 375 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 376 | description='API.INVALID_EMAIL') |
||
| 377 | email = str.lower(str.strip(new_values['data']['email'])) |
||
| 378 | |||
| 379 | match = re.match(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) |
||
| 380 | if match is None: |
||
| 381 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 382 | description='API.INVALID_EMAIL') |
||
| 383 | |||
| 384 | if 'phone' not in new_values['data'].keys() or \ |
||
| 385 | not isinstance(new_values['data']['phone'], str) or \ |
||
| 386 | len(str.strip(new_values['data']['phone'])) == 0: |
||
| 387 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 388 | description='API.INVALID_USER_PHONE') |
||
| 389 | phone = str.strip(new_values['data']['phone']) |
||
| 390 | |||
| 391 | if 'description' in new_values['data'].keys() and \ |
||
| 392 | new_values['data']['description'] is not None and \ |
||
| 393 | len(str(new_values['data']['description'])) > 0: |
||
| 394 | description = str.strip(new_values['data']['description']) |
||
| 395 | else: |
||
| 396 | description = None |
||
| 397 | |||
| 398 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 399 | cursor = cnx.cursor() |
||
| 400 | |||
| 401 | cursor.execute(" SELECT name " |
||
| 402 | " FROM tbl_contacts " |
||
| 403 | " WHERE id = %s ", (id_,)) |
||
| 404 | if cursor.fetchone() is None: |
||
| 405 | cursor.close() |
||
| 406 | cnx.close() |
||
| 407 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 408 | description='API.CONTACT_NOT_FOUND') |
||
| 409 | |||
| 410 | cursor.execute(" SELECT name " |
||
| 411 | " FROM tbl_contacts " |
||
| 412 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
| 413 | if cursor.fetchone() is not None: |
||
| 414 | cursor.close() |
||
| 415 | cnx.close() |
||
| 416 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 417 | description='API.CONTACT_NAME_IS_ALREADY_IN_USE') |
||
| 418 | |||
| 419 | update_row = (" UPDATE tbl_contacts " |
||
| 420 | " SET name = %s, email = %s, " |
||
| 421 | " phone = %s, description = %s " |
||
| 422 | " WHERE id = %s ") |
||
| 423 | cursor.execute(update_row, (name, |
||
| 424 | email, |
||
| 425 | phone, |
||
| 426 | description, |
||
| 427 | id_,)) |
||
| 428 | cnx.commit() |
||
| 429 | |||
| 430 | cursor.close() |
||
| 431 | cnx.close() |
||
| 432 | |||
| 433 | resp.status = falcon.HTTP_200 |
||
| 434 | |||
| 435 |