| Total Complexity | 67 |
| Total Lines | 306 |
| Duplicated Lines | 8.17 % |
| 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 emailserver 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 falcon |
||
| 2 | import json |
||
| 3 | import mysql.connector |
||
| 4 | import config |
||
| 5 | import base64 |
||
| 6 | import re |
||
| 7 | |||
| 8 | |||
| 9 | class EmailServerCollection: |
||
| 10 | @staticmethod |
||
| 11 | def __init__(): |
||
| 12 | pass |
||
| 13 | |||
| 14 | @staticmethod |
||
| 15 | def on_options(req, resp): |
||
| 16 | resp.status = falcon.HTTP_200 |
||
| 17 | |||
| 18 | @staticmethod |
||
| 19 | def on_get(req, resp): |
||
| 20 | cnx = mysql.connector.connect(**config.myems_fdd_db) |
||
| 21 | cursor = cnx.cursor() |
||
| 22 | |||
| 23 | query = (" SELECT id, host, port, requires_authentication, user_name, password, from_addr " |
||
| 24 | " FROM tbl_email_servers ") |
||
| 25 | cursor.execute(query) |
||
| 26 | rows = cursor.fetchall() |
||
| 27 | cursor.close() |
||
| 28 | cnx.disconnect() |
||
| 29 | |||
| 30 | result = list() |
||
| 31 | if rows is not None and len(rows) > 0: |
||
| 32 | for row in rows: |
||
| 33 | meta_result = {"id": row[0], |
||
| 34 | "host": row[1], |
||
| 35 | "port": row[2], |
||
| 36 | "requires_authentication": bool(row[3]), |
||
| 37 | "user_name": row[4], |
||
| 38 | "password": str(base64.b64decode(bytearray(row[5], 'utf-8')), 'utf-8') |
||
| 39 | if row[5] is not None else None, |
||
| 40 | "from_addr": row[6]} |
||
| 41 | result.append(meta_result) |
||
| 42 | |||
| 43 | resp.body = json.dumps(result) |
||
| 44 | |||
| 45 | @staticmethod |
||
| 46 | def on_post(req, resp): |
||
| 47 | """Handles POST requests""" |
||
| 48 | try: |
||
| 49 | raw_json = req.stream.read().decode('utf-8') |
||
| 50 | except Exception as ex: |
||
| 51 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) |
||
| 52 | |||
| 53 | new_values = json.loads(raw_json, encoding='utf-8') |
||
| 54 | |||
| 55 | if 'host' not in new_values['data'].keys() or \ |
||
| 56 | not isinstance(new_values['data']['host'], str) or \ |
||
| 57 | len(str.strip(new_values['data']['host'])) == 0: |
||
| 58 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 59 | description='API.INVALID_EMAIL_SERVER_HOST') |
||
| 60 | |||
| 61 | host = str.strip(new_values['data']['host']) |
||
| 62 | |||
| 63 | if 'port' not in new_values['data'].keys() or \ |
||
| 64 | not isinstance(new_values['data']['port'], int) or \ |
||
| 65 | new_values['data']['port'] <= 0: |
||
| 66 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 67 | description='API.INVALID_PORT') |
||
| 68 | port = float(new_values['data']['port']) |
||
| 69 | |||
| 70 | if 'requires_authentication' not in new_values['data'].keys() or \ |
||
| 71 | not isinstance(new_values['data']['requires_authentication'], bool): |
||
| 72 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 73 | description='API.INVALID_REQUIRES_AUTHENTICATION') |
||
| 74 | requires_authentication = new_values['data']['requires_authentication'] |
||
| 75 | |||
| 76 | if requires_authentication: |
||
| 77 | if 'user_name' not in new_values['data'].keys() or \ |
||
| 78 | not isinstance(new_values['data']['user_name'], str) or \ |
||
| 79 | len(str.strip(new_values['data']['user_name'])) == 0: |
||
| 80 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 81 | description='API.INVALID_USER_NAME') |
||
| 82 | user_name = new_values['data']['user_name'] |
||
| 83 | else: |
||
| 84 | user_name = None |
||
| 85 | |||
| 86 | if requires_authentication: |
||
| 87 | if 'password' not in new_values['data'].keys() or \ |
||
| 88 | not isinstance(new_values['data']['password'], str) or \ |
||
| 89 | len(str.strip(new_values['data']['password'])) == 0: |
||
| 90 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 91 | description='API.INVALID_PASSWORD') |
||
| 92 | password = base64.b64encode(bytearray(new_values['data']['password'], 'utf-8')) |
||
| 93 | else: |
||
| 94 | password = None |
||
| 95 | |||
| 96 | if 'from_addr' not in new_values['data'].keys() or \ |
||
| 97 | not isinstance(new_values['data']['from_addr'], str) or \ |
||
| 98 | len(str.strip(new_values['data']['from_addr'])) == 0: |
||
| 99 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 100 | description='API.INVALID_FROM_ADDR') |
||
| 101 | from_addr = new_values['data']['from_addr'] |
||
| 102 | |||
| 103 | match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', from_addr) |
||
| 104 | if match is None: |
||
| 105 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 106 | description='API.INVALID_FROM_ADDR') |
||
| 107 | |||
| 108 | cnx = mysql.connector.connect(**config.myems_fdd_db) |
||
| 109 | cursor = cnx.cursor() |
||
| 110 | |||
| 111 | cursor.execute(" SELECT host " |
||
| 112 | " FROM tbl_email_servers " |
||
| 113 | " WHERE host = %s ", (host,)) |
||
| 114 | if cursor.fetchone() is not None: |
||
| 115 | cursor.close() |
||
| 116 | cnx.disconnect() |
||
| 117 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
| 118 | description='API.EMAIL_SERVER_HOST_IS_ALREADY_IN_USE') |
||
| 119 | |||
| 120 | add_value = (" INSERT INTO tbl_email_servers " |
||
| 121 | " (host, port, requires_authentication, user_name, password, from_addr) " |
||
| 122 | " VALUES (%s, %s, %s, %s, %s, %s) ") |
||
| 123 | cursor.execute(add_value, (host, |
||
| 124 | port, |
||
| 125 | requires_authentication, |
||
| 126 | user_name, |
||
| 127 | password, |
||
| 128 | from_addr)) |
||
| 129 | new_id = cursor.lastrowid |
||
| 130 | cnx.commit() |
||
| 131 | cursor.close() |
||
| 132 | cnx.disconnect() |
||
| 133 | |||
| 134 | resp.status = falcon.HTTP_201 |
||
| 135 | resp.location = '/emailservers/' + str(new_id) |
||
| 136 | |||
| 137 | |||
| 138 | class EmailServerItem: |
||
| 139 | @staticmethod |
||
| 140 | def __init__(): |
||
| 141 | pass |
||
| 142 | |||
| 143 | @staticmethod |
||
| 144 | def on_options(req, resp, id_): |
||
| 145 | resp.status = falcon.HTTP_200 |
||
| 146 | |||
| 147 | @staticmethod |
||
| 148 | def on_get(req, resp, id_): |
||
| 149 | if not id_.isdigit() or int(id_) <= 0: |
||
| 150 | raise falcon.HTTPError(falcon.HTTP_400, '400 Bad Request') |
||
| 151 | |||
| 152 | cnx = mysql.connector.connect(**config.myems_fdd_db) |
||
| 153 | cursor = cnx.cursor() |
||
| 154 | |||
| 155 | query = (" SELECT id, host, port, requires_authentication, user_name, password, from_addr " |
||
| 156 | " FROM tbl_email_servers " |
||
| 157 | " WHERE id = %s ") |
||
| 158 | cursor.execute(query, (id_,)) |
||
| 159 | row = cursor.fetchone() |
||
| 160 | cursor.close() |
||
| 161 | cnx.disconnect() |
||
| 162 | if row is None: |
||
| 163 | raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND') |
||
| 164 | |||
| 165 | result = {"id": row[0], |
||
| 166 | "host": row[1], |
||
| 167 | "port": row[2], |
||
| 168 | "requires_authentication": bool(row[3]), |
||
| 169 | "user_name": row[4], |
||
| 170 | "password": str(base64.b64decode(bytearray(row[5], 'utf-8')), 'utf-8') |
||
| 171 | if row[5] is not None else None, |
||
| 172 | "from_addr": row[5]} |
||
| 173 | resp.body = json.dumps(result) |
||
| 174 | |||
| 175 | View Code Duplication | @staticmethod |
|
|
|
|||
| 176 | def on_delete(req, resp, id_): |
||
| 177 | if not id_.isdigit() or int(id_) <= 0: |
||
| 178 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 179 | description='API.INVALID_EMAIL_SERVER_ID') |
||
| 180 | |||
| 181 | cnx = mysql.connector.connect(**config.myems_fdd_db) |
||
| 182 | cursor = cnx.cursor() |
||
| 183 | |||
| 184 | cursor.execute(" SELECT host " |
||
| 185 | " FROM tbl_email_servers " |
||
| 186 | " WHERE id = %s ", (id_,)) |
||
| 187 | if cursor.fetchone() is None: |
||
| 188 | cursor.close() |
||
| 189 | cnx.disconnect() |
||
| 190 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 191 | description='API.EMAIL_SERVER_NOT_FOUND') |
||
| 192 | |||
| 193 | cursor.execute(" DELETE FROM tbl_email_servers WHERE id = %s ", (id_,)) |
||
| 194 | cnx.commit() |
||
| 195 | |||
| 196 | cursor.close() |
||
| 197 | cnx.disconnect() |
||
| 198 | |||
| 199 | resp.status = falcon.HTTP_204 |
||
| 200 | |||
| 201 | @staticmethod |
||
| 202 | def on_put(req, resp, id_): |
||
| 203 | """Handles PUT requests""" |
||
| 204 | try: |
||
| 205 | raw_json = req.stream.read().decode('utf-8') |
||
| 206 | except Exception as ex: |
||
| 207 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
| 208 | |||
| 209 | if not id_.isdigit() or int(id_) <= 0: |
||
| 210 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 211 | description='API.INVALID_EMAIL_SERVER_ID') |
||
| 212 | |||
| 213 | new_values = json.loads(raw_json, encoding='utf-8') |
||
| 214 | if 'host' not in new_values['data'].keys() or \ |
||
| 215 | not isinstance(new_values['data']['host'], str) or \ |
||
| 216 | len(str.strip(new_values['data']['host'])) == 0: |
||
| 217 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 218 | description='API.INVALID_EMAIL_SERVER_HOST') |
||
| 219 | |||
| 220 | host = str.strip(new_values['data']['host']) |
||
| 221 | |||
| 222 | if 'port' not in new_values['data'].keys() or \ |
||
| 223 | not isinstance(new_values['data']['port'], int) or \ |
||
| 224 | new_values['data']['port'] <= 0: |
||
| 225 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 226 | description='API.INVALID_PORT') |
||
| 227 | port = float(new_values['data']['port']) |
||
| 228 | |||
| 229 | if 'requires_authentication' not in new_values['data'].keys() or \ |
||
| 230 | not isinstance(new_values['data']['requires_authentication'], bool): |
||
| 231 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 232 | description='API.INVALID_REQUIRES_AUTHENTICATION') |
||
| 233 | requires_authentication = new_values['data']['requires_authentication'] |
||
| 234 | |||
| 235 | if requires_authentication: |
||
| 236 | if 'user_name' not in new_values['data'].keys() or \ |
||
| 237 | not isinstance(new_values['data']['user_name'], str) or \ |
||
| 238 | len(str.strip(new_values['data']['user_name'])) == 0: |
||
| 239 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 240 | description='API.INVALID_USER_NAME') |
||
| 241 | user_name = new_values['data']['user_name'] |
||
| 242 | else: |
||
| 243 | user_name = None |
||
| 244 | |||
| 245 | if requires_authentication: |
||
| 246 | if 'password' not in new_values['data'].keys() or \ |
||
| 247 | not isinstance(new_values['data']['password'], str) or \ |
||
| 248 | len(str.strip(new_values['data']['password'])) == 0: |
||
| 249 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 250 | description='API.INVALID_PASSWORD') |
||
| 251 | password = base64.b64encode(bytearray(new_values['data']['password'], 'utf-8')) |
||
| 252 | else: |
||
| 253 | password = None |
||
| 254 | |||
| 255 | if 'from_addr' not in new_values['data'].keys() or \ |
||
| 256 | not isinstance(new_values['data']['from_addr'], str) or \ |
||
| 257 | len(str.strip(new_values['data']['from_addr'])) == 0: |
||
| 258 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 259 | description='API.INVALID_FROM_ADDR') |
||
| 260 | from_addr = new_values['data']['from_addr'] |
||
| 261 | |||
| 262 | match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', from_addr) |
||
| 263 | if match is None: |
||
| 264 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 265 | description='API.INVALID_FROM_ADDR') |
||
| 266 | |||
| 267 | cnx = mysql.connector.connect(**config.myems_fdd_db) |
||
| 268 | cursor = cnx.cursor() |
||
| 269 | |||
| 270 | cursor.execute(" SELECT id " |
||
| 271 | " FROM tbl_email_servers " |
||
| 272 | " WHERE id = %s ", |
||
| 273 | (id_,)) |
||
| 274 | if cursor.fetchone() is None: |
||
| 275 | cursor.close() |
||
| 276 | cnx.disconnect() |
||
| 277 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 278 | description='API.EMAIL_SERVER_NOT_FOUND') |
||
| 279 | |||
| 280 | cursor.execute(" SELECT host " |
||
| 281 | " FROM tbl_email_servers " |
||
| 282 | " WHERE host = %s AND id != %s ", (host, id_)) |
||
| 283 | if cursor.fetchone() is not None: |
||
| 284 | cursor.close() |
||
| 285 | cnx.disconnect() |
||
| 286 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
| 287 | description='API.EMAIL_SERVER_HOST_IS_ALREADY_IN_USE') |
||
| 288 | |||
| 289 | update_row = (" UPDATE tbl_email_servers " |
||
| 290 | " SET host = %s, port = %s, requires_authentication = %s, " |
||
| 291 | " user_name = %s, password = %s, from_addr = %s " |
||
| 292 | " WHERE id = %s ") |
||
| 293 | cursor.execute(update_row, (host, |
||
| 294 | port, |
||
| 295 | requires_authentication, |
||
| 296 | user_name, |
||
| 297 | password, |
||
| 298 | from_addr, |
||
| 299 | id_,)) |
||
| 300 | cnx.commit() |
||
| 301 | |||
| 302 | cursor.close() |
||
| 303 | cnx.disconnect() |
||
| 304 | |||
| 305 | resp.status = falcon.HTTP_200 |
||
| 306 |