core.contact.ContactItem.on_delete()   F
last analyzed

Complexity

Conditions 24

Size

Total Lines 149
Code Lines 111

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 111
dl 0
loc 149
rs 0
c 0
b 0
f 0
cc 24
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

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