Passed
Push — master ( 42322a...183c79 )
by
unknown
10:22 queued 16s
created

core.sensor.SensorClone.on_post()   D

Complexity

Conditions 12

Size

Total Lines 74
Code Lines 57

Duplication

Lines 24
Ratio 32.43 %

Importance

Changes 0
Metric Value
eloc 57
dl 24
loc 74
rs 4.7672
c 0
b 0
f 0
cc 12
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.sensor.SensorClone.on_post() 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 View Code Duplication
class SensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
11
    def __init__(self):
12
        """"Initializes SensorCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        _ = req
18
        resp.status = falcon.HTTP_200
19
20
    @staticmethod
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, description "
32
                 " FROM tbl_sensors "
33
                 " ORDER BY id ")
34
        cursor.execute(query)
35
        rows_sensors = cursor.fetchall()
36
37
        result = list()
38
        if rows_sensors is not None and len(rows_sensors) > 0:
39
            for row in rows_sensors:
40
                meta_result = {"id": row[0],
41
                               "name": row[1],
42
                               "uuid": row[2],
43
                               "description": row[3]}
44
                result.append(meta_result)
45
46
        cursor.close()
47
        cnx.close()
48
        resp.text = json.dumps(result)
49
50
    @staticmethod
51
    @user_logger
52
    def on_post(req, resp):
53
        """Handles POST requests"""
54
        admin_control(req)
55
        try:
56
            raw_json = req.stream.read().decode('utf-8')
57
        except Exception as ex:
58
            print(str(ex))
59
            raise falcon.HTTPError(status=falcon.HTTP_400,
60
                                   title='API.BAD_REQUEST',
61
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
62
63
        new_values = json.loads(raw_json)
64
65
        if 'name' not in new_values['data'].keys() or \
66
                not isinstance(new_values['data']['name'], str) or \
67
                len(str.strip(new_values['data']['name'])) == 0:
68
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
69
                                   description='API.INVALID_SENSOR_NAME')
70
        name = str.strip(new_values['data']['name'])
71
72
        if 'description' in new_values['data'].keys() and \
73
                new_values['data']['description'] is not None and \
74
                len(str(new_values['data']['description'])) > 0:
75
            description = str.strip(new_values['data']['description'])
76
        else:
77
            description = None
78
79
        cnx = mysql.connector.connect(**config.myems_system_db)
80
        cursor = cnx.cursor()
81
82
        cursor.execute(" SELECT name "
83
                       " FROM tbl_sensors "
84
                       " WHERE name = %s ", (name,))
85
        if cursor.fetchone() is not None:
86
            cursor.close()
87
            cnx.close()
88
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
89
                                   description='API.SENSOR_NAME_IS_ALREADY_IN_USE')
90
91
        add_values = (" INSERT INTO tbl_sensors "
92
                      "    (name, uuid, description) "
93
                      " VALUES (%s, %s, %s) ")
94
        cursor.execute(add_values, (name,
95
                                    str(uuid.uuid4()),
96
                                    description))
97
        new_id = cursor.lastrowid
98
        cnx.commit()
99
        cursor.close()
100
        cnx.close()
101
102
        resp.status = falcon.HTTP_201
103
        resp.location = '/sensors/' + str(new_id)
104
105
106
class SensorItem:
107
    def __init__(self):
108
        """"Initializes SensorItem"""
109
        pass
110
111
    @staticmethod
112
    def on_options(req, resp, id_):
113
        _ = req
114
        resp.status = falcon.HTTP_200
115
        _ = id_
116
117
    @staticmethod
118
    def on_get(req, resp, id_):
119
        if 'API-KEY' not in req.headers or \
120
                not isinstance(req.headers['API-KEY'], str) or \
121
                len(str.strip(req.headers['API-KEY'])) == 0:
122
            access_control(req)
123
        else:
124
            api_key_control(req)
125
        if not id_.isdigit() or int(id_) <= 0:
126
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
127
                                   description='API.INVALID_SENSOR_ID')
128
129
        cnx = mysql.connector.connect(**config.myems_system_db)
130
        cursor = cnx.cursor()
131
132
        query = (" SELECT id, name, uuid, description "
133
                 " FROM tbl_sensors "
134
                 " WHERE id = %s ")
135
        cursor.execute(query, (id_,))
136
        row = cursor.fetchone()
137
        cursor.close()
138
        cnx.close()
139
140
        if row is None:
141
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
142
                                   description='API.SENSOR_NOT_FOUND')
143
        else:
144
            meta_result = {"id": row[0],
145
                           "name": row[1],
146
                           "uuid": row[2],
147
                           "description": row[3]}
148
149
        resp.text = json.dumps(meta_result)
150
151 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
152
    @user_logger
153
    def on_delete(req, resp, id_):
154
        admin_control(req)
155
        if not id_.isdigit() or int(id_) <= 0:
156
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
157
                                   description='API.INVALID_SENSOR_ID')
158
159
        cnx = mysql.connector.connect(**config.myems_system_db)
160
        cursor = cnx.cursor()
161
162
        cursor.execute(" SELECT name "
163
                       " FROM tbl_sensors "
164
                       " WHERE id = %s ", (id_,))
165
        if cursor.fetchone() is None:
166
            cursor.close()
167
            cnx.close()
168
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
169
                                   description='API.SENSOR_NOT_FOUND')
170
171
        # check relation with spaces
172
        cursor.execute(" SELECT id "
173
                       " FROM tbl_spaces_sensors "
174
                       " WHERE sensor_id = %s ", (id_,))
175
        rows_spaces = cursor.fetchall()
176
        if rows_spaces is not None and len(rows_spaces) > 0:
177
            cursor.close()
178
            cnx.close()
179
            raise falcon.HTTPError(status=falcon.HTTP_400,
180
                                   title='API.BAD_REQUEST',
181
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
182
183
        # check relation with tenants
184
        cursor.execute(" SELECT id "
185
                       " FROM tbl_tenants_sensors "
186
                       " WHERE sensor_id = %s ", (id_,))
187
        rows_tenants = cursor.fetchall()
188
        if rows_tenants is not None and len(rows_tenants) > 0:
189
            cursor.close()
190
            cnx.close()
191
            raise falcon.HTTPError(status=falcon.HTTP_400,
192
                                   title='API.BAD_REQUEST',
193
                                   description='API.THERE_IS_RELATION_WITH_TENANTS')
194
195
        # check relation with stores
196
        cursor.execute(" SELECT store_id "
197
                       " FROM tbl_stores_sensors "
198
                       " WHERE sensor_id = %s ", (id_,))
199
        rows_stores = cursor.fetchall()
200
        if rows_stores is not None and len(rows_stores) > 0:
201
            cursor.close()
202
            cnx.close()
203
            raise falcon.HTTPError(status=falcon.HTTP_400,
204
                                   title='API.BAD_REQUEST',
205
                                   description='API.THERE_IS_RELATION_WITH_STORES')
206
207
        # check relation with microgrid
208
        cursor.execute(" SELECT id "
209
                       " FROM tbl_microgrids_sensors "
210
                       " WHERE sensor_id = %s ", (id_,))
211
        rows_microgrid = cursor.fetchall()
212
        if rows_microgrid is not None and len(rows_microgrid) > 0:
213
            cursor.close()
214
            cnx.close()
215
            raise falcon.HTTPError(status=falcon.HTTP_400,
216
                                   title='API.BAD_REQUEST',
217
                                   description='API.THERE_IS_RELATION_WITH_MICROGRIDS')
218
219
        # check relation with shopfloors
220
        cursor.execute(" SELECT id "
221
                       " FROM tbl_shopfloors_sensors "
222
                       " WHERE sensor_id = %s ", (id_,))
223
        rows_shopfloor = cursor.fetchall()
224
        if rows_shopfloor is not None and len(rows_shopfloor) > 0:
225
            cursor.close()
226
            cnx.close()
227
            raise falcon.HTTPError(status=falcon.HTTP_400,
228
                                   title='API.BAD_REQUEST',
229
                                   description='API.THERE_IS_RELATION_WITH_SHOPFLOORS')
230
231
        # delete relation with points
232
        cursor.execute(" DELETE FROM tbl_sensors_points WHERE sensor_id = %s ", (id_,))
233
234
        cursor.execute(" DELETE FROM tbl_sensors WHERE id = %s ", (id_,))
235
        cnx.commit()
236
237
        cursor.close()
238
        cnx.close()
239
240
        resp.status = falcon.HTTP_204
241
242 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
243
    @user_logger
244
    def on_put(req, resp, id_):
245
        """Handles PUT requests"""
246
        admin_control(req)
247
        try:
248
            raw_json = req.stream.read().decode('utf-8')
249
        except Exception as ex:
250
            print(str(ex))
251
            raise falcon.HTTPError(status=falcon.HTTP_400,
252
                                   title='API.BAD_REQUEST',
253
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
254
255
        if not id_.isdigit() or int(id_) <= 0:
256
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
257
                                   description='API.INVALID_SENSOR_ID')
258
259
        new_values = json.loads(raw_json)
260
261
        if 'name' not in new_values['data'].keys() or \
262
                not isinstance(new_values['data']['name'], str) or \
263
                len(str.strip(new_values['data']['name'])) == 0:
264
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
265
                                   description='API.INVALID_SENSOR_NAME')
266
        name = str.strip(new_values['data']['name'])
267
268
        if 'description' in new_values['data'].keys() and \
269
                new_values['data']['description'] is not None and \
270
                len(str(new_values['data']['description'])) > 0:
271
            description = str.strip(new_values['data']['description'])
272
        else:
273
            description = None
274
275
        cnx = mysql.connector.connect(**config.myems_system_db)
276
        cursor = cnx.cursor()
277
278
        cursor.execute(" SELECT name "
279
                       " FROM tbl_sensors "
280
                       " WHERE id = %s ", (id_,))
281
        if cursor.fetchone() is None:
282
            cursor.close()
283
            cnx.close()
284
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
285
                                   description='API.SENSOR_NOT_FOUND')
286
287
        cursor.execute(" SELECT name "
288
                       " FROM tbl_sensors "
289
                       " WHERE name = %s AND id != %s ", (name, id_))
290
        if cursor.fetchone() is not None:
291
            cursor.close()
292
            cnx.close()
293
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
294
                                   description='API.SENSOR_NAME_IS_ALREADY_IN_USE')
295
296
        update_row = (" UPDATE tbl_sensors "
297
                      " SET name = %s, description = %s "
298
                      " WHERE id = %s ")
299
        cursor.execute(update_row, (name,
300
                                    description,
301
                                    id_,))
302
        cnx.commit()
303
304
        cursor.close()
305
        cnx.close()
306
307
        resp.status = falcon.HTTP_200
308
309
310
class SensorPointCollection:
311
    def __init__(self):
312
        """"Initializes SensorPointCollection"""
313
        pass
314
315
    @staticmethod
316
    def on_options(req, resp, id_):
317
        _ = req
318
        resp.status = falcon.HTTP_200
319
        _ = id_
320
321 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
322
    def on_get(req, resp, id_):
323
        if 'API-KEY' not in req.headers or \
324
                not isinstance(req.headers['API-KEY'], str) or \
325
                len(str.strip(req.headers['API-KEY'])) == 0:
326
            access_control(req)
327
        else:
328
            api_key_control(req)
329
        if not id_.isdigit() or int(id_) <= 0:
330
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
331
                                   description='API.INVALID_SENSOR_ID')
332
333
        cnx = mysql.connector.connect(**config.myems_system_db)
334
        cursor = cnx.cursor()
335
336
        cursor.execute(" SELECT name "
337
                       " FROM tbl_sensors "
338
                       " WHERE id = %s ", (id_,))
339
        if cursor.fetchone() is None:
340
            cursor.close()
341
            cnx.close()
342
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
343
                                   description='API.SENSOR_NOT_FOUND')
344
345
        query = (" SELECT p.id, p.name, "
346
                 "        ds.id, ds.name, ds.uuid, "
347
                 "        p.address "
348
                 " FROM tbl_points p, tbl_sensors_points sp, tbl_data_sources ds "
349
                 " WHERE sp.sensor_id = %s AND p.id = sp.point_id AND p.data_source_id = ds.id "
350
                 " ORDER BY p.name ")
351
        cursor.execute(query, (id_,))
352
        rows = cursor.fetchall()
353
354
        result = list()
355
        if rows is not None and len(rows) > 0:
356
            for row in rows:
357
                meta_result = {"id": row[0], "name": row[1],
358
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
359
                               "address": row[5]}
360
                result.append(meta_result)
361
362
        resp.text = json.dumps(result)
363
364 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
365
    @user_logger
366
    def on_post(req, resp, id_):
367
        """Handles POST requests"""
368
        admin_control(req)
369
        try:
370
            raw_json = req.stream.read().decode('utf-8')
371
        except Exception as ex:
372
            print(str(ex))
373
            raise falcon.HTTPError(status=falcon.HTTP_400,
374
                                   title='API.BAD_REQUEST',
375
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
376
377
        if not id_.isdigit() or int(id_) <= 0:
378
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
379
                                   description='API.INVALID_SENSOR_ID')
380
381
        new_values = json.loads(raw_json)
382
383
        cnx = mysql.connector.connect(**config.myems_system_db)
384
        cursor = cnx.cursor()
385
386
        cursor.execute(" SELECT name "
387
                       " from tbl_sensors "
388
                       " WHERE id = %s ", (id_,))
389
        if cursor.fetchone() is None:
390
            cursor.close()
391
            cnx.close()
392
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
393
                                   description='API.SENSOR_NOT_FOUND')
394
395
        cursor.execute(" SELECT name "
396
                       " FROM tbl_points "
397
                       " WHERE id = %s ", (new_values['data']['point_id'],))
398
        if cursor.fetchone() is None:
399
            cursor.close()
400
            cnx.close()
401
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
402
                                   description='API.POINT_NOT_FOUND')
403
404
        query = (" SELECT id " 
405
                 " FROM tbl_sensors_points "
406
                 " WHERE sensor_id = %s AND point_id = %s")
407
        cursor.execute(query, (id_, new_values['data']['point_id'],))
408
        if cursor.fetchone() is not None:
409
            cursor.close()
410
            cnx.close()
411
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
412
                                   description='API.SENSOR_POINT_RELATION_EXISTS')
413
414
        add_row = (" INSERT INTO tbl_sensors_points (sensor_id, point_id) "
415
                   " VALUES (%s, %s) ")
416
        cursor.execute(add_row, (id_, new_values['data']['point_id'],))
417
        cnx.commit()
418
        cursor.close()
419
        cnx.close()
420
421
        resp.status = falcon.HTTP_201
422
        resp.location = '/sensors/' + str(id_) + '/points/' + str(new_values['data']['point_id'])
423
424
425
class SensorPointItem:
426
    def __init__(self):
427
        """"Initializes SensorPointItem"""
428
        pass
429
430
    @staticmethod
431
    def on_options(req, resp, id_, pid):
432
        _ = req
433
        resp.status = falcon.HTTP_200
434
        _ = id_
435
436
    @staticmethod
437
    @user_logger
438
    def on_delete(req, resp, id_, pid):
439
        admin_control(req)
440
        if not id_.isdigit() or int(id_) <= 0:
441
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
442
                                   description='API.INVALID_SENSOR_ID')
443
444
        if not pid.isdigit() or int(pid) <= 0:
445
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
446
                                   description='API.INVALID_POINT_ID')
447
448
        cnx = mysql.connector.connect(**config.myems_system_db)
449
        cursor = cnx.cursor()
450
451
        cursor.execute(" SELECT name "
452
                       " FROM tbl_sensors "
453
                       " WHERE id = %s ", (id_,))
454
        if cursor.fetchone() is None:
455
            cursor.close()
456
            cnx.close()
457
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
458
                                   description='API.SENSOR_NOT_FOUND')
459
460
        cursor.execute(" SELECT name "
461
                       " FROM tbl_points "
462
                       " WHERE id = %s ", (pid,))
463
        if cursor.fetchone() is None:
464
            cursor.close()
465
            cnx.close()
466
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
467
                                   description='API.POINT_NOT_FOUND')
468
469
        cursor.execute(" SELECT id "
470
                       " FROM tbl_sensors_points "
471
                       " WHERE sensor_id = %s AND point_id = %s ", (id_, pid))
472
        if cursor.fetchone() is None:
473
            cursor.close()
474
            cnx.close()
475
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
476
                                   description='API.SENSOR_POINT_RELATION_NOT_FOUND')
477
478
        cursor.execute(" DELETE FROM tbl_sensors_points WHERE sensor_id = %s AND point_id = %s ", (id_, pid))
479
        cnx.commit()
480
481
        cursor.close()
482
        cnx.close()
483
484
        resp.status = falcon.HTTP_204
485
486
487
class SensorExport:
488
    def __init__(self):
489
        pass
490
491
    @staticmethod
492
    def on_options(req, resp, id_):
493
        _ = req
494
        resp.status = falcon.HTTP_200
495
        _ = id_
496
497
    @staticmethod
498
    def on_get(req, resp, id_):
499
        if 'API-KEY' not in req.headers or \
500
                not isinstance(req.headers['API-KEY'], str) or \
501
                len(str.strip(req.headers['API-KEY'])) == 0:
502
            access_control(req)
503
        else:
504
            api_key_control(req)
505
        if not id_.isdigit() or int(id_) <= 0:
506
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
507
                                   description='API.INVALID_SENSOR_ID')
508
509
        cnx = mysql.connector.connect(**config.myems_system_db)
510
        cursor = cnx.cursor()
511
512
        query = (" SELECT id, name, uuid, description "
513
                 " FROM tbl_sensors "
514
                 " WHERE id = %s ")
515
        cursor.execute(query, (id_,))
516
        row = cursor.fetchone()
517
518 View Code Duplication
        if row is None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
519
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
520
                                   description='API.SENSOR_NOT_FOUND')
521
        else:
522
            meta_result = {"id": row[0],
523
                           "name": row[1],
524
                           "uuid": row[2],
525
                           "description": row[3],
526
                           "points": None}
527
            query = (" SELECT p.id, p.name "
528
                     " FROM tbl_points p, tbl_sensors_points sp "
529
                     " WHERE sp.sensor_id = %s AND p.id = sp.point_id "
530
                     " ORDER BY p.id ")
531
            cursor.execute(query, (id_,))
532
            rows = cursor.fetchall()
533
            result = list()
534
            if rows is not None and len(rows) > 0:
535
                for row in rows:
536
                    point_result = {"id": row[0], "name": row[1]}
537
                    result.append(point_result)
538
                meta_result['points'] = result
539
            cursor.close()
540
            cnx.close()
541
        resp.text = json.dumps(meta_result)
542
543
544
class SensorImport:
545
    def __init__(self):
546
        """"Initializes SensorImport"""
547
        pass
548
549
    @staticmethod
550
    def on_options(req, resp):
551
        _ = req
552
        resp.status = falcon.HTTP_200
553
554
    @staticmethod
555
    @user_logger
556
    def on_post(req, resp):
557
        """Handles POST requests"""
558
        admin_control(req)
559
        try:
560
            raw_json = req.stream.read().decode('utf-8')
561
        except Exception as ex:
562
            print(str(ex))
563
            raise falcon.HTTPError(status=falcon.HTTP_400,
564
                                   title='API.BAD_REQUEST',
565
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
566
567
        new_values = json.loads(raw_json)
568
569
        if 'name' not in new_values.keys() or \
570
                not isinstance(new_values['name'], str) or \
571
                len(str.strip(new_values['name'])) == 0:
572
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
573
                                   description='API.INVALID_SENSOR_NAME')
574
        name = str.strip(new_values['name'])
575
576
        if 'description' in new_values.keys() and \
577
                new_values['description'] is not None and \
578
                len(str(new_values['description'])) > 0:
579
            description = str.strip(new_values['description'])
580
        else:
581
            description = None
582
583
        cnx = mysql.connector.connect(**config.myems_system_db)
584
        cursor = cnx.cursor()
585
586
        cursor.execute(" SELECT name "
587
                       " FROM tbl_sensors "
588
                       " WHERE name = %s ", (name,))
589
        if cursor.fetchone() is not None:
590
            cursor.close()
591
            cnx.close()
592
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
593
                                   description='API.SENSOR_NAME_IS_ALREADY_IN_USE')
594
595
        add_values = (" INSERT INTO tbl_sensors "
596
                      "    (name, uuid, description) "
597
                      " VALUES (%s, %s, %s) ")
598
        cursor.execute(add_values, (name,
599
                                    str(uuid.uuid4()),
600
                                    description))
601
        new_id = cursor.lastrowid
602
        if 'points' in new_values.keys() and \
603
                new_values['points'] is not None and \
604
                len(new_values['points']) > 0:
605
            for point in new_values['points']:
606
                if 'id' in point and isinstance(point['id'], int):
607
                    cursor.execute(" SELECT name "
608
                                   " FROM tbl_points "
609
                                   " WHERE id = %s ", (point['id'],))
610
                    if cursor.fetchone() is None:
611
                        cursor.close()
612
                        cnx.close()
613
                        raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
614
                                               description='API.POINT_NOT_FOUND')
615
616
                    add_row = (" INSERT INTO tbl_sensors_points (sensor_id, point_id) "
617
                               " VALUES (%s, %s) ")
618
                    cursor.execute(add_row, (new_id, point['id'],))
619
                else:
620
                    raise falcon.HTTPError(status=falcon.HTTP_400, title='API.NOT_FOUND',
621
                                           description='API.INVALID_POINT_ID')
622
        cnx.commit()
623
        cursor.close()
624
        cnx.close()
625
626
        resp.status = falcon.HTTP_201
627
        resp.location = '/sensors/' + str(new_id)
628
629
630
class SensorClone:
631
632
    def __init__(self):
633
        """"Initializes SensorClone"""
634
        pass
635
636
    @staticmethod
637
    def on_options(req, resp, id_):
638
        _ = req
639
        resp.status = falcon.HTTP_200
640
        _ = id_
641
642
    @staticmethod
643
    @user_logger
644
    def on_post(req, resp, id_):
645
        admin_control(req)
646
        if not id_.isdigit() or int(id_) <= 0:
647
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
648
                                   description='API.INVALID_SENSOR_ID')
649
650
        cnx = mysql.connector.connect(**config.myems_system_db)
651
        cursor = cnx.cursor()
652
653
        query = (" SELECT id, name, uuid, description "
654
                 " FROM tbl_sensors "
655
                 " WHERE id = %s ")
656
        cursor.execute(query, (id_,))
657
        row = cursor.fetchone()
658 View Code Duplication
        if row is None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
659
            cursor.close()
660
            cnx.close()
661
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
662
                                   description='API.SENSOR_NOT_FOUND')
663
        else:
664
            meta_result = {"id": row[0],
665
                           "name": row[1],
666
                           "uuid": row[2],
667
                           "description": row[3],
668
                           "points": None}
669
670
            query = (" SELECT p.id, p.name "
671
                     " FROM tbl_points p, tbl_sensors_points sp "
672
                     " WHERE sp.sensor_id = %s AND p.id = sp.point_id "
673
                     " ORDER BY p.id ")
674
            cursor.execute(query, (id_,))
675
            rows = cursor.fetchall()
676
            result = list()
677
            if rows is not None and len(rows) > 0:
678
                for row in rows:
679
                    point_result = {"id": row[0], "name": row[1]}
680
                    result.append(point_result)
681
                meta_result['points'] = result
682
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
683
        if config.utc_offset[0] == '-':
684
            timezone_offset = -timezone_offset
685
        new_name = (str.strip(meta_result['name']) +
686
                    (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
687
688
        add_values = (" INSERT INTO tbl_sensors "
689
                      "    (name, uuid, description) "
690
                      " VALUES (%s, %s, %s) ")
691
        cursor.execute(add_values, (new_name,
692
                                    str(uuid.uuid4()),
693
                                    meta_result['description']))
694
        new_id = cursor.lastrowid
695
        if meta_result['points'] is not None and len(meta_result['points']) > 0:
696
            for point in meta_result['points']:
697
                cursor.execute(" SELECT name "
698
                               " FROM tbl_points "
699
                               " WHERE id = %s ", (point['id'],))
700
                if cursor.fetchone() is None:
701
                    cursor.close()
702
                    cnx.close()
703
                    raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
704
                                           description='API.POINT_NOT_FOUND')
705
706
                add_row = (" INSERT INTO tbl_sensors_points (sensor_id, point_id) "
707
                           " VALUES (%s, %s) ")
708
                cursor.execute(add_row, (new_id, point['id'],))
709
710
        cnx.commit()
711
        cursor.close()
712
        cnx.close()
713
714
        resp.status = falcon.HTTP_201
715
        resp.location = '/sensors/' + str(new_id)
716