Total Complexity | 59 |
Total Lines | 313 |
Duplicated Lines | 32.27 % |
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 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 falcon |
||
2 | import simplejson as json |
||
3 | import mysql.connector |
||
4 | import config |
||
5 | import uuid |
||
6 | import re |
||
7 | |||
8 | |||
9 | class ContactCollection: |
||
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_system_db) |
||
21 | cursor = cnx.cursor() |
||
22 | |||
23 | query = (" SELECT id, name, uuid, " |
||
24 | " email, phone, description " |
||
25 | " FROM tbl_contacts " |
||
26 | " ORDER BY name ") |
||
27 | cursor.execute(query) |
||
28 | rows = cursor.fetchall() |
||
29 | cursor.close() |
||
30 | cnx.disconnect() |
||
31 | |||
32 | result = list() |
||
33 | if rows is not None and len(rows) > 0: |
||
34 | for row in rows: |
||
35 | meta_result = {"id": row[0], |
||
36 | "name": row[1], |
||
37 | "uuid": row[2], |
||
38 | "email": row[3], |
||
39 | "phone": row[4], |
||
40 | "description": row[5]} |
||
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.EXCEPTION', description=ex) |
||
52 | |||
53 | new_values = json.loads(raw_json, encoding='utf-8') |
||
54 | |||
55 | if 'name' not in new_values['data'].keys() or \ |
||
56 | not isinstance(new_values['data']['name'], str) or \ |
||
57 | len(str.strip(new_values['data']['name'])) == 0: |
||
58 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
59 | description='API.INVALID_USER_NAME') |
||
60 | name = str.strip(new_values['data']['name']) |
||
61 | |||
62 | if 'email' not in new_values['data'].keys() or \ |
||
63 | not isinstance(new_values['data']['email'], str) or \ |
||
64 | len(str.strip(new_values['data']['email'])) == 0: |
||
65 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
66 | description='API.INVALID_EMAIL') |
||
67 | email = str.strip(new_values['data']['email']) |
||
68 | |||
69 | match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) |
||
70 | if match is None: |
||
71 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
72 | description='API.INVALID_EMAIL') |
||
73 | |||
74 | if 'phone' not in new_values['data'].keys() or \ |
||
75 | not isinstance(new_values['data']['phone'], str) or \ |
||
76 | len(str.strip(new_values['data']['phone'])) == 0: |
||
77 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
78 | description='API.INVALID_USER_PHONE') |
||
79 | phone = str.strip(new_values['data']['phone']) |
||
80 | |||
81 | if 'description' in new_values['data'].keys() and \ |
||
82 | new_values['data']['description'] is not None and \ |
||
83 | len(str(new_values['data']['description'])) > 0: |
||
84 | description = str.strip(new_values['data']['description']) |
||
85 | else: |
||
86 | description = None |
||
87 | |||
88 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
89 | cursor = cnx.cursor() |
||
90 | |||
91 | cursor.execute(" SELECT name " |
||
92 | " FROM tbl_contacts " |
||
93 | " WHERE name = %s ", (name,)) |
||
94 | if cursor.fetchone() is not None: |
||
95 | cursor.close() |
||
96 | cnx.disconnect() |
||
97 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
98 | description='API.CONTACT_NAME_IS_ALREADY_IN_USE') |
||
99 | |||
100 | add_row = (" INSERT INTO tbl_contacts " |
||
101 | " (name, uuid, email, phone, description) " |
||
102 | " VALUES (%s, %s, %s, %s, %s) ") |
||
103 | |||
104 | cursor.execute(add_row, (name, |
||
105 | str(uuid.uuid4()), |
||
106 | email, |
||
107 | phone, |
||
108 | description)) |
||
109 | new_id = cursor.lastrowid |
||
110 | cnx.commit() |
||
111 | cursor.close() |
||
112 | cnx.disconnect() |
||
113 | |||
114 | resp.status = falcon.HTTP_201 |
||
115 | resp.location = '/contacts/' + str(new_id) |
||
116 | |||
117 | |||
118 | class ContactItem: |
||
119 | @staticmethod |
||
120 | def __init__(): |
||
121 | pass |
||
122 | |||
123 | @staticmethod |
||
124 | def on_options(req, resp, id_): |
||
125 | resp.status = falcon.HTTP_200 |
||
126 | |||
127 | View Code Duplication | @staticmethod |
|
|
|||
128 | def on_get(req, resp, id_): |
||
129 | if not id_.isdigit() or int(id_) <= 0: |
||
130 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
131 | description='API.INVALID_CONTACT_ID') |
||
132 | |||
133 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
134 | cursor = cnx.cursor() |
||
135 | |||
136 | query = (" SELECT id, name, uuid, email, phone, description " |
||
137 | " FROM tbl_contacts " |
||
138 | " WHERE id = %s ") |
||
139 | cursor.execute(query, (id_,)) |
||
140 | row = cursor.fetchone() |
||
141 | cursor.close() |
||
142 | cnx.disconnect() |
||
143 | |||
144 | if row is None: |
||
145 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
146 | description='API.CONTACT_NOT_FOUND') |
||
147 | |||
148 | result = {"id": row[0], |
||
149 | "name": row[1], |
||
150 | "uuid": row[2], |
||
151 | "email": row[3], |
||
152 | "phone": row[4], |
||
153 | "description": row[5]} |
||
154 | resp.body = json.dumps(result) |
||
155 | |||
156 | View Code Duplication | @staticmethod |
|
157 | def on_delete(req, resp, id_): |
||
158 | if not id_.isdigit() or int(id_) <= 0: |
||
159 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
160 | description='API.INVALID_CONTACT_ID') |
||
161 | |||
162 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
163 | cursor = cnx.cursor() |
||
164 | |||
165 | cursor.execute(" SELECT name " |
||
166 | " FROM tbl_contacts " |
||
167 | " WHERE id = %s ", (id_,)) |
||
168 | if cursor.fetchone() is None: |
||
169 | cursor.close() |
||
170 | cnx.disconnect() |
||
171 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
172 | description='API.CONTACT_NOT_FOUND') |
||
173 | |||
174 | # check relation with shopfloors |
||
175 | cursor.execute(" SELECT id " |
||
176 | " FROM tbl_shopfloors " |
||
177 | " WHERE contact_id = %s ", (id_,)) |
||
178 | rows_shopfloors = cursor.fetchall() |
||
179 | if rows_shopfloors is not None and len(rows_shopfloors) > 0: |
||
180 | cursor.close() |
||
181 | cnx.disconnect() |
||
182 | raise falcon.HTTPError(falcon.HTTP_400, |
||
183 | title='API.BAD_REQUEST', |
||
184 | description='API.THERE_IS_RELATION_WITH_SHOPFLOORS') |
||
185 | |||
186 | # check relation with spaces |
||
187 | cursor.execute(" SELECT id " |
||
188 | " FROM tbl_spaces " |
||
189 | " WHERE contact_id = %s ", (id_,)) |
||
190 | rows_spaces = cursor.fetchall() |
||
191 | if rows_spaces is not None and len(rows_spaces) > 0: |
||
192 | cursor.close() |
||
193 | cnx.disconnect() |
||
194 | raise falcon.HTTPError(falcon.HTTP_400, |
||
195 | title='API.BAD_REQUEST', |
||
196 | description='API.THERE_IS_RELATION_WITH_SPACES') |
||
197 | |||
198 | # check relation with stores |
||
199 | cursor.execute(" SELECT id " |
||
200 | " FROM tbl_stores " |
||
201 | " WHERE contact_id = %s ", (id_,)) |
||
202 | rows_stores = cursor.fetchall() |
||
203 | if rows_stores is not None and len(rows_stores) > 0: |
||
204 | cursor.close() |
||
205 | cnx.disconnect() |
||
206 | raise falcon.HTTPError(falcon.HTTP_400, |
||
207 | title='API.BAD_REQUEST', |
||
208 | description='API.THERE_IS_RELATION_WITH_STORES') |
||
209 | |||
210 | # check relation with tenants |
||
211 | cursor.execute(" SELECT id " |
||
212 | " FROM tbl_tenants " |
||
213 | " WHERE contact_id = %s ", (id_,)) |
||
214 | rows_tenants = cursor.fetchall() |
||
215 | if rows_tenants is not None and len(rows_tenants) > 0: |
||
216 | cursor.close() |
||
217 | cnx.disconnect() |
||
218 | raise falcon.HTTPError(falcon.HTTP_400, |
||
219 | title='API.BAD_REQUEST', |
||
220 | description='API.THERE_IS_RELATION_WITH_TENANTS') |
||
221 | |||
222 | cursor.execute(" DELETE FROM tbl_contacts WHERE id = %s ", (id_,)) |
||
223 | cnx.commit() |
||
224 | |||
225 | cursor.close() |
||
226 | cnx.disconnect() |
||
227 | |||
228 | resp.status = falcon.HTTP_204 |
||
229 | |||
230 | @staticmethod |
||
231 | def on_put(req, resp, id_): |
||
232 | """Handles PUT requests""" |
||
233 | try: |
||
234 | raw_json = req.stream.read().decode('utf-8') |
||
235 | except Exception as ex: |
||
236 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
237 | |||
238 | if not id_.isdigit() or int(id_) <= 0: |
||
239 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
240 | description='API.INVALID_') |
||
241 | |||
242 | new_values = json.loads(raw_json, encoding='utf-8') |
||
243 | |||
244 | if 'name' not in new_values['data'].keys() or \ |
||
245 | not isinstance(new_values['data']['name'], str) or \ |
||
246 | len(str.strip(new_values['data']['name'])) == 0: |
||
247 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
248 | description='API.INVALID_CONTACT_NAME') |
||
249 | name = str.strip(new_values['data']['name']) |
||
250 | |||
251 | if 'email' not in new_values['data'].keys() or \ |
||
252 | not isinstance(new_values['data']['email'], str) or \ |
||
253 | len(str.strip(new_values['data']['email'])) == 0: |
||
254 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
255 | description='API.INVALID_EMAIL') |
||
256 | email = str.strip(new_values['data']['email']) |
||
257 | |||
258 | match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) |
||
259 | if match is None: |
||
260 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
261 | description='API.INVALID_EMAIL') |
||
262 | |||
263 | if 'phone' not in new_values['data'].keys() or \ |
||
264 | not isinstance(new_values['data']['phone'], str) or \ |
||
265 | len(str.strip(new_values['data']['phone'])) == 0: |
||
266 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
267 | description='API.INVALID_USER_PHONE') |
||
268 | phone = str.strip(new_values['data']['phone']) |
||
269 | |||
270 | if 'description' in new_values['data'].keys() and \ |
||
271 | new_values['data']['description'] is not None and \ |
||
272 | len(str(new_values['data']['description'])) > 0: |
||
273 | description = str.strip(new_values['data']['description']) |
||
274 | else: |
||
275 | description = None |
||
276 | |||
277 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
278 | cursor = cnx.cursor() |
||
279 | |||
280 | cursor.execute(" SELECT name " |
||
281 | " FROM tbl_contacts " |
||
282 | " WHERE id = %s ", (id_,)) |
||
283 | if cursor.fetchone() is None: |
||
284 | cursor.close() |
||
285 | cnx.disconnect() |
||
286 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
287 | description='API.CONTACT_NOT_FOUND') |
||
288 | |||
289 | cursor.execute(" SELECT name " |
||
290 | " FROM tbl_contacts " |
||
291 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
292 | if cursor.fetchone() is not None: |
||
293 | cursor.close() |
||
294 | cnx.disconnect() |
||
295 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
296 | description='API.CONTACT_NAME_IS_ALREADY_IN_USE') |
||
297 | |||
298 | update_row = (" UPDATE tbl_contacts " |
||
299 | " SET name = %s, email = %s, " |
||
300 | " phone = %s, description = %s " |
||
301 | " WHERE id = %s ") |
||
302 | cursor.execute(update_row, (name, |
||
303 | email, |
||
304 | phone, |
||
305 | description, |
||
306 | id_,)) |
||
307 | cnx.commit() |
||
308 | |||
309 | cursor.close() |
||
310 | cnx.disconnect() |
||
311 | |||
312 | resp.status = falcon.HTTP_200 |
||
313 | |||
314 |