core.controlmode.ControlModeExport.on_get()   F
last analyzed

Complexity

Conditions 14

Size

Total Lines 60
Code Lines 45

Duplication

Lines 60
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 45
dl 60
loc 60
rs 3.6
c 0
b 0
f 0
cc 14
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.controlmode.ControlModeExport.on_get() 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 re
8
import config
9
10
11
class ControlModeCollection:
12
    def __init__(self):
13
        """"Initializes"""
14
        pass
15
16
    @staticmethod
17
    def on_options(req, resp):
18
        _ = req
19
        resp.status = falcon.HTTP_200
20
21
    @staticmethod
22
    def on_get(req, resp):
23
        if 'API-KEY' not in req.headers or \
24
                not isinstance(req.headers['API-KEY'], str) or \
25
                len(str.strip(req.headers['API-KEY'])) == 0:
26
            access_control(req)
27
        else:
28
            api_key_control(req)
29
        cnx = mysql.connector.connect(**config.myems_system_db)
30
        cursor = cnx.cursor()
31
32
        query = (" SELECT id, name, uuid, is_active "
33
                 " FROM tbl_control_modes "
34
                 " ORDER BY id ")
35
        cursor.execute(query)
36
        rows = cursor.fetchall()
37
38
        result = list()
39
        if rows is not None and len(rows) > 0:
40
            for row in rows:
41
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2], "is_active": bool(row[3]), 'times': list()}
42
43
                query = (" SELECT start_time_of_day, end_time_of_day, power_value "
44
                         " FROM tbl_control_modes_times "
45
                         " WHERE control_mode_id = %s  "
46
                         " ORDER BY id")
47
                cursor.execute(query, (meta_result['id'],))
48
                rows_times = cursor.fetchall()
49
                if rows_times is not None and len(rows_times) > 0:
50
                    for row_time in rows_times:
51
                        start_time_of_day = str(row_time[0])
52
                        parts = start_time_of_day.split(':')
53
                        hour = parts[0].zfill(2)
54
                        minute = parts[1].zfill(2) if len(parts) > 1 else '00'
55
                        second = parts[2].zfill(2) if len(parts) > 2 else '00'
56
                        start_time_of_day = f"{hour}:{minute}:{second}"
57
58
                        end_time_of_day = str(row_time[1])
59
                        parts = end_time_of_day.split(':')
60
                        hour = parts[0].zfill(2)
61
                        minute = parts[1].zfill(2) if len(parts) > 1 else '00'
62
                        second = parts[2].zfill(2) if len(parts) > 2 else '00'
63
                        end_time_of_day = f"{hour}:{minute}:{second}"
64
65
                        meta_data = {"start_time_of_day": start_time_of_day,
66
                                     "end_time_of_day": end_time_of_day,
67
                                     "power_value": row_time[2]}
68
                        meta_result['times'].append(meta_data)
69
                result.append(meta_result)
70
71
        cursor.close()
72
        cnx.close()
73
74
        resp.text = json.dumps(result)
75
76
    @staticmethod
77
    @user_logger
78
    def on_post(req, resp):
79
        """Handles POST requests"""
80
        admin_control(req)
81
        try:
82
            raw_json = req.stream.read().decode('utf-8')
83
        except Exception as ex:
84
            print(str(ex))
85
            raise falcon.HTTPError(status=falcon.HTTP_400,
86
                                   title='API.BAD_REQUEST',
87
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
88
        new_values = json.loads(raw_json)
89
90
        if 'name' not in new_values['data'].keys() or \
91
                not isinstance(new_values['data']['name'], str) or \
92
                len(str.strip(new_values['data']['name'])) == 0:
93
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
94
                                   description='API.INVALID_CONTROL_MODE_NAME')
95
        name = str.strip(new_values['data']['name'])
96
97
        if 'is_active' not in new_values['data'].keys() or \
98
                not isinstance(new_values['data']['is_active'], bool):
99
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
100
                                   description='API.INVALID_IS_ACTIVE_VALUE')
101
        is_active = new_values['data']['is_active']
102
103
        if new_values['data']['times'] is None:
104
            raise falcon.HTTPError(status=falcon.HTTP_400,
105
                                   title='API.BAD_REQUEST',
106
                                   description='API.INVALID_CONTROL_MODE_TIMES')
107
108
        cnx = mysql.connector.connect(**config.myems_system_db)
109
        cursor = cnx.cursor()
110
111
        cursor.execute(" SELECT name "
112
                       " FROM tbl_control_modes "
113
                       " WHERE name = %s ", (name,))
114
        if cursor.fetchone() is not None:
115
            cursor.close()
116
            cnx.close()
117
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
118
                                   description='API.CONTROL_MODE_NAME_IS_ALREADY_IN_USE')
119
120
        add_row = (" INSERT INTO tbl_control_modes "
121
                   "             (name, uuid, is_active ) "
122
                   " VALUES (%s, %s, %s) ")
123
        cursor.execute(add_row, (name,
124
                                 str(uuid.uuid4()),
125
                                 is_active))
126
        new_id = cursor.lastrowid
127
        cnx.commit()
128
        for item in new_values['data']['times']:
129
            add_time = (" INSERT INTO tbl_control_modes_times "
130
                        "             (control_mode_id, start_time_of_day, end_time_of_day, power_value) "
131
                        " VALUES (%s, %s, %s, %s) ")
132
            cursor.execute(add_time, (new_id,
133
                                      item['start_time_of_day'],
134
                                      item['end_time_of_day'],
135
                                      item['power_value']))
136
            cnx.commit()
137
138
        cursor.close()
139
        cnx.close()
140
141
        resp.status = falcon.HTTP_201
142
        resp.location = '/controlmodes/' + str(new_id)
143
144
145
class ControlModeItem:
146
    def __init__(self):
147
        """"Initializes"""
148
        pass
149
150
    @staticmethod
151
    def on_options(req, resp, id_):
152
        _ = req
153
        resp.status = falcon.HTTP_200
154
        _ = id_
155
156 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
157
    def on_get(req, resp, id_):
158
        """Handles GET requests"""
159
        if 'API-KEY' not in req.headers or \
160
                not isinstance(req.headers['API-KEY'], str) or \
161
                len(str.strip(req.headers['API-KEY'])) == 0:
162
            access_control(req)
163
        else:
164
            api_key_control(req)
165
        if not id_.isdigit() or int(id_) <= 0:
166
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
167
                                   description='API.INVALID_CONTROL_MODE_ID')
168
169
        cnx = mysql.connector.connect(**config.myems_system_db)
170
        cursor = cnx.cursor()
171
172
        query = (" SELECT id, name, uuid, is_active "
173
                 " FROM tbl_control_modes "
174
                 " WHERE id = %s ")
175
        cursor.execute(query, (id_,))
176
        row = cursor.fetchone()
177
        if row is None:
178
            cursor.close()
179
            cnx.close()
180
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
181
                                   description='API.CONTROL_MODE_NOT_FOUND')
182
183
        result = {"id": row[0], "name": row[1], "uuid": row[2], "is_active": bool(row[3]), 'times': list()}
184
185
        query = (" SELECT start_time_of_day, end_time_of_day, power_value "
186
                 " FROM tbl_control_modes_times "
187
                 " WHERE control_mode_id = %s  "
188
                 " ORDER BY id ")
189
        cursor.execute(query, (result['id'],))
190
        rows_times = cursor.fetchall()
191
        if rows_times is not None and len(rows_times) > 0:
192
            for row_time in rows_times:
193
                start_time_of_day = str(row_time[0])
194
                parts = start_time_of_day.split(':')
195
                hour = parts[0].zfill(2)
196
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
197
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
198
                start_time_of_day = f"{hour}:{minute}:{second}"
199
200
                end_time_of_day = str(row_time[1])
201
                parts = end_time_of_day.split(':')
202
                hour = parts[0].zfill(2)
203
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
204
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
205
                end_time_of_day = f"{hour}:{minute}:{second}"
206
207
                meta_data = {"start_time_of_day": start_time_of_day,
208
                             "end_time_of_day": end_time_of_day,
209
                             "power_value": row_time[2]}
210
                result['times'].append(meta_data)
211
212
        cursor.close()
213
        cnx.close()
214
215
        resp.text = json.dumps(result)
216
217
    @staticmethod
218
    @user_logger
219
    def on_delete(req, resp, id_):
220
        """Handles DELETE requests"""
221
        admin_control(req)
222
        if not id_.isdigit() or int(id_) <= 0:
223
            raise falcon.HTTPError(status=falcon.HTTP_400,
224
                                   title='API.BAD_REQUEST',
225
                                   description='API.INVALID_CONTROL_MODE_ID')
226
227
        cnx = mysql.connector.connect(**config.myems_system_db)
228
        cursor = cnx.cursor()
229
230
        cursor.execute(" SELECT name "
231
                       " FROM tbl_control_modes "
232
                       " WHERE id = %s ", (id_,))
233
        if cursor.fetchone() is None:
234
            cursor.close()
235
            cnx.close()
236
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
237
                                   description='API.CONTROL_MODE_NOT_FOUND')
238
239
        cursor.execute(" DELETE FROM tbl_control_modes_times WHERE control_mode_id = %s ", (id_,))
240
        cnx.commit()
241
242
        cursor.execute(" DELETE FROM tbl_control_modes WHERE id = %s ", (id_,))
243
        cnx.commit()
244
245
        cursor.close()
246
        cnx.close()
247
248
        resp.status = falcon.HTTP_204
249
250
    @staticmethod
251
    @user_logger
252
    def on_put(req, resp, id_):
253
        """Handles PUT requests"""
254
        admin_control(req)
255
        try:
256
            raw_json = req.stream.read().decode('utf-8')
257
        except Exception as ex:
258
            print(str(ex))
259
            raise falcon.HTTPError(status=falcon.HTTP_400,
260
                                   title='API.BAD_REQUEST',
261
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
262
263
        if not id_.isdigit() or int(id_) <= 0:
264
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
265
                                   description='API.INVALID_CONTROL_MODE_ID')
266
267
        new_values = json.loads(raw_json)
268
269
        if 'name' not in new_values['data'].keys() or \
270
                not isinstance(new_values['data']['name'], str) or \
271
                len(str.strip(new_values['data']['name'])) == 0:
272
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
273
                                   description='API.INVALID_CONTROL_MODE_NAME')
274
        name = str.strip(new_values['data']['name'])
275
276
        if 'is_active' not in new_values['data'].keys() or \
277
                not isinstance(new_values['data']['is_active'], bool):
278
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
279
                                   description='API.INVALID_IS_ACTIVE_VALUE')
280
        is_active = new_values['data']['is_active']
281
282
        if 'times' not in new_values['data'].keys() or \
283
                not isinstance(new_values['data']['times'], list) or \
284
                len(new_values['data']['times']) == 0:
285
            raise falcon.HTTPError(status=falcon.HTTP_400,
286
                                   title='API.BAD_REQUEST',
287
                                   description='API.INVALID_CONTROL_MODE_TIMES')
288
289
        cnx = mysql.connector.connect(**config.myems_system_db)
290
        cursor = cnx.cursor()
291
292
        # check if the control mode exists
293
        query = (" SELECT name "
294
                 " FROM tbl_control_modes "
295
                 " WHERE id = %s ")
296
        cursor.execute(query, (id_,))
297
        cursor.fetchone()
298
299
        if cursor.rowcount != 1:
300
            cursor.close()
301
            cnx.close()
302
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
303
                                   description='API.CONTROL_MODE_NOT_FOUND')
304
305
        cursor.execute(" SELECT name "
306
                       " FROM tbl_control_modes "
307
                       " WHERE name = %s AND id != %s ", (name, id_))
308
        if cursor.fetchone() is not None:
309
            cursor.close()
310
            cnx.close()
311
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
312
                                   description='API.CONTROL_MODE_NAME_IS_ALREADY_IN_USE')
313
314
        # update control mode
315
        update_row = (" UPDATE tbl_control_modes "
316
                      " SET name = %s, is_active = %s "
317
                      " WHERE id = %s ")
318
        cursor.execute(update_row, (name,
319
                                    is_active,
320
                                    id_,))
321
        cnx.commit()
322
323
        # remove all (possible) exist times
324
        cursor.execute(" DELETE FROM tbl_control_modes_times "
325
                       " WHERE control_mode_id = %s ",
326
                       (id_,))
327
        cnx.commit()
328
329
        for item in new_values['data']['times']:
330
            add_time = (" INSERT INTO tbl_control_modes_times "
331
                        "             (control_mode_id, start_time_of_day, end_time_of_day, power_value) "
332
                        " VALUES (%s, %s, %s, %s) ")
333
            cursor.execute(add_time, (id_,
334
                                      item['start_time_of_day'],
335
                                      item['end_time_of_day'],
336
                                      item['power_value']))
337
            cnx.commit()
338
        cursor.close()
339
        cnx.close()
340
        resp.status = falcon.HTTP_200
341
342
343
class ControlModeExport:
344
    def __init__(self):
345
        """"Initializes"""
346
        pass
347
348
    @staticmethod
349
    def on_options(req, resp, id_):
350
        _ = req
351
        resp.status = falcon.HTTP_200
352
        _ = id_
353
354 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
355
    def on_get(req, resp, id_):
356
        """Handles GET requests"""
357
        if 'API-KEY' not in req.headers or \
358
                not isinstance(req.headers['API-KEY'], str) or \
359
                len(str.strip(req.headers['API-KEY'])) == 0:
360
            access_control(req)
361
        else:
362
            api_key_control(req)
363
        if not id_.isdigit() or int(id_) <= 0:
364
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
365
                                   description='API.INVALID_CONTROL_MODE_ID')
366
367
        cnx = mysql.connector.connect(**config.myems_system_db)
368
        cursor = cnx.cursor()
369
370
        query = (" SELECT id, name, uuid, is_active "
371
                 " FROM tbl_control_modes "
372
                 " WHERE id = %s ")
373
        cursor.execute(query, (id_,))
374
        row = cursor.fetchone()
375
        if row is None:
376
            cursor.close()
377
            cnx.close()
378
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
379
                                   description='API.CONTROL_MODE_NOT_FOUND')
380
381
        result = {"id": row[0], "name": row[1], "uuid": row[2], "is_active": bool(row[3]), 'times': list()}
382
383
        query = (" SELECT start_time_of_day, end_time_of_day, power_value "
384
                 " FROM tbl_control_modes_times "
385
                 " WHERE control_mode_id = %s  "
386
                 " ORDER BY id")
387
        cursor.execute(query, (result['id'],))
388
        rows_times = cursor.fetchall()
389
        if rows_times is not None and len(rows_times) > 0:
390
            for row_time in rows_times:
391
                start_time_of_day = str(row_time[0])
392
                parts = start_time_of_day.split(':')
393
                hour = parts[0].zfill(2)
394
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
395
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
396
                start_time_of_day = f"{hour}:{minute}:{second}"
397
398
                end_time_of_day = str(row_time[1])
399
                parts = end_time_of_day.split(':')
400
                hour = parts[0].zfill(2)
401
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
402
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
403
                end_time_of_day = f"{hour}:{minute}:{second}"
404
405
                meta_data = {"start_time_of_day": start_time_of_day,
406
                             "end_time_of_day": end_time_of_day,
407
                             "power_value": row_time[2]}
408
                result['times'].append(meta_data)
409
410
        cursor.close()
411
        cnx.close()
412
413
        resp.text = json.dumps(result)
414
415
416
class ControlModeImport:
417
    def __init__(self):
418
        """"Initializes"""
419
        pass
420
421
    @staticmethod
422
    def on_options(req, resp):
423
        _ = req
424
        resp.status = falcon.HTTP_200
425
426
    @staticmethod
427
    @user_logger
428
    def on_post(req, resp):
429
        """Handles POST requests"""
430
        admin_control(req)
431
        try:
432
            raw_json = req.stream.read().decode('utf-8')
433
        except Exception as ex:
434
            print(str(ex))
435
            raise falcon.HTTPError(status=falcon.HTTP_400,
436
                                   title='API.BAD_REQUEST',
437
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
438
        new_values = json.loads(raw_json)
439
440
        if 'name' not in new_values.keys() or \
441
                not isinstance(new_values['name'], str) or \
442
                len(str.strip(new_values['name'])) == 0:
443
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
444
                                   description='API.INVALID_METER_NAME')
445
        name = str.strip(new_values['name'])
446
447
        if 'is_active' not in new_values.keys() or \
448
                not isinstance(new_values['is_active'], bool):
449
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
450
                                   description='API.INVALID_IS_ACTIVE_VALUE')
451
        is_active = new_values['is_active']
452
453
        if 'times' not in new_values.keys() or \
454
                not isinstance(new_values['times'], list) or \
455
                len(new_values['times']) == 0:
456
            raise falcon.HTTPError(status=falcon.HTTP_400,
457
                                   title='API.BAD_REQUEST',
458
                                   description='API.INVALID_CONTROL_MODE_TIMES')
459
460
        cnx = mysql.connector.connect(**config.myems_system_db)
461
        cursor = cnx.cursor()
462
463
        cursor.execute(" SELECT name "
464
                       " FROM tbl_control_modes "
465
                       " WHERE name = %s ", (name,))
466
        if cursor.fetchone() is not None:
467
            cursor.close()
468
            cnx.close()
469
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
470
                                   description='API.CONTROL_MODE_NAME_IS_ALREADY_IN_USE')
471
472
        add_row = (" INSERT INTO tbl_control_modes "
473
                   "             (name, uuid, is_active ) "
474
                   " VALUES (%s, %s, %s) ")
475
        cursor.execute(add_row, (name,
476
                                 str(uuid.uuid4()),
477
                                 is_active,))
478
        new_id = cursor.lastrowid
479
        cnx.commit()
480
481
        for item in new_values['times']:
482
            add_time = (" INSERT INTO tbl_control_modes_times "
483
                        "             (control_mode_id, start_time_of_day, end_time_of_day, power_value) "
484
                        " VALUES (%s, %s, %s, %s) ")
485
            cursor.execute(add_time, (new_id,
486
                                      item['start_time_of_day'],
487
                                      item['end_time_of_day'],
488
                                      item['power_value']))
489
            cnx.commit()
490
491
        cursor.close()
492
        cnx.close()
493
494
        resp.status = falcon.HTTP_201
495
        resp.location = '/controlmodes/' + str(new_id)
496
497
498
class ControlModeClone:
499
    def __init__(self):
500
        """"Initializes"""
501
        pass
502
503
    @staticmethod
504
    def on_options(req, resp, id_):
505
        _ = req
506
        resp.status = falcon.HTTP_200
507
        _ = id_
508
509
    @staticmethod
510
    @user_logger
511
    def on_post(req, resp, id_):
512
        admin_control(req)
513
        if not id_.isdigit() or int(id_) <= 0:
514
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
515
                                   description='API.INVALID_CONTROL_MODE_ID')
516
517
        cnx = mysql.connector.connect(**config.myems_system_db)
518
        cursor = cnx.cursor()
519
520
        query = (" SELECT id, name, uuid, is_active "
521
                 " FROM tbl_control_modes "
522
                 " WHERE id = %s ")
523
        cursor.execute(query, (id_,))
524
        row = cursor.fetchone()
525
        if row is None:
526
            cursor.close()
527
            cnx.close()
528
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
529
                                   description='API.CONTROL_MODE_NOT_FOUND')
530
531
        result = {"id": row[0], "name": row[1], "uuid": row[2], "is_active": bool(row[3]), 'times': list()}
532
533
        query = (" SELECT start_time_of_day, end_time_of_day, power_value "
534
                 " FROM tbl_control_modes_times "
535
                 " WHERE control_mode_id = %s  "
536
                 " ORDER BY id")
537
        cursor.execute(query, (result['id'],))
538
        rows_times = cursor.fetchall()
539
        if rows_times is not None and len(rows_times) > 0:
540
            for row_time in rows_times:
541
                start_time_of_day = str(row_time[0])
542
                parts = start_time_of_day.split(':')
543
                hour = parts[0].zfill(2)
544
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
545
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
546
                start_time_of_day = f"{hour}:{minute}:{second}"
547
548
                end_time_of_day = str(row_time[1])
549
                parts = end_time_of_day.split(':')
550
                hour = parts[0].zfill(2)
551
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
552
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
553
                end_time_of_day = f"{hour}:{minute}:{second}"
554
555
                meta_data = {"start_time_of_day": start_time_of_day,
556
                             "end_time_of_day": end_time_of_day,
557
                             "power_value": row_time[2]}
558
                result['times'].append(meta_data)
559
560
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
561
        if config.utc_offset[0] == '-':
562
            timezone_offset = -timezone_offset
563
        new_name = (str.strip(result['name']) +
564
                    (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
565
        add_row = (" INSERT INTO tbl_control_modes "
566
                   "             (name, uuid, is_active) "
567
                   " VALUES (%s, %s, %s) ")
568
        cursor.execute(add_row, (new_name,
569
                                 str(uuid.uuid4()),
570
                                 result['is_active']))
571
        new_id = cursor.lastrowid
572
        cnx.commit()
573
        for item in result['times']:
574
            add_time = (" INSERT INTO tbl_control_modes_times "
575
                        "             (control_mode_id, start_time_of_day, end_time_of_day, power_value) "
576
                        " VALUES (%s, %s, %s, %s) ")
577
            cursor.execute(add_time, (new_id,
578
                                      item['start_time_of_day'],
579
                                      item['end_time_of_day'],
580
                                      item['power_value']))
581
            cnx.commit()
582
        cursor.close()
583
        cnx.close()
584
585
        resp.status = falcon.HTTP_201
586
        resp.location = '/controlmodes/' + str(new_id)
587
588
589
class ControlModeTimeCollection:
590
    def __init__(self):
591
        """Initializes"""
592
        pass
593
594
    @staticmethod
595
    def on_options(req, resp, id_):
596
        _ = req
597
        resp.status = falcon.HTTP_200
598
        _ = id_
599
600
    @staticmethod
601
    def on_get(req, resp, id_):
602
        if 'API-KEY' not in req.headers or \
603
                not isinstance(req.headers['API-KEY'], str) or \
604
                len(str.strip(req.headers['API-KEY'])) == 0:
605
            access_control(req)
606
        else:
607
            api_key_control(req)
608
        if not id_.isdigit() or int(id_) <= 0:
609
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
610
                                   description='API.INVALID_CONTROL_MODE_ID')
611
612
        cnx = mysql.connector.connect(**config.myems_system_db)
613
        cursor = cnx.cursor()
614
615
        query = (" SELECT id, name "
616
                 " FROM tbl_points ")
617
        cursor.execute(query)
618
        rows_points = cursor.fetchall()
619
620
        point_dict = dict()
621
        if rows_points is not None and len(rows_points) > 0:
622
            for row in rows_points:
623
                point_dict[row[0]] = {"id": row[0],
624
                                      "name": row[1]}
625
626
        cursor.execute(" SELECT name "
627
                       " FROM tbl_control_modes "
628
                       " WHERE id = %s ", (id_,))
629
        if cursor.fetchone() is None:
630
            cursor.close()
631
            cnx.close()
632
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
633
                                   description='API.CONTROL_MODE_NOT_FOUND')
634
635
        query = (" SELECT id, start_time_of_day, end_time_of_day, "
636
                 "        power_value, power_point_id, power_equation, description "
637
                 " FROM tbl_control_modes_times "
638
                 " WHERE control_mode_id = %s "
639
                 " ORDER BY id ")
640
        cursor.execute(query, (id_,))
641
        rows_times = cursor.fetchall()
642
643
        result = list()
644
        if rows_times is not None and len(rows_times) > 0:
645
            for row_time in rows_times:
646
                start_time_of_day = str(row_time[1])
647
                parts = start_time_of_day.split(':')
648
                hour = parts[0].zfill(2)
649
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
650
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
651
                start_time_of_day = f"{hour}:{minute}:{second}"
652
653
                end_time_of_day = str(row_time[2])
654
                parts = end_time_of_day.split(':')
655
                hour = parts[0].zfill(2)
656
                minute = parts[1].zfill(2) if len(parts) > 1 else '00'
657
                second = parts[2].zfill(2) if len(parts) > 2 else '00'
658
                end_time_of_day = f"{hour}:{minute}:{second}"
659
660
                meta_result = {"id": row[0],
0 ignored issues
show
introduced by
The variable row does not seem to be defined for all execution paths.
Loading history...
661
                               "start_time_of_day": start_time_of_day,
662
                               "end_time_of_day": end_time_of_day,
663
                               "power_value": row_time[3],
664
                               "power_point": point_dict.get(row_time[4], None),
665
                               "power_equation": row_time[5],
666
                               "description": row_time[6]}
667
                result.append(meta_result)
668
        print(result)
669
        cursor.close()
670
        cnx.close()
671
        resp.text = json.dumps(result)
672
673
    @staticmethod
674
    @user_logger
675
    def on_post(req, resp, id_):
676
        """Handles POST requests"""
677
        admin_control(req)
678
        if not id_.isdigit() or int(id_) <= 0:
679
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
680
                                   description='API.INVALID_CONTROL_MODE_ID')
681
        try:
682
            raw_json = req.stream.read().decode('utf-8')
683
        except Exception as ex:
684
            print(str(ex))
685
            raise falcon.HTTPError(status=falcon.HTTP_400,
686
                                   title='API.BAD_REQUEST',
687
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
688
689
        new_values = json.loads(raw_json)
690
691
        if 'start_time_of_day' not in new_values['data'].keys() or \
692
                not isinstance(new_values['data']['start_time_of_day'], str) or \
693
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
694
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
695
                                   description='API.INVALID_START_TIME_OF_DAY')
696
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
697
698
        if 'end_time_of_day' not in new_values['data'].keys() or \
699
                not isinstance(new_values['data']['end_time_of_day'], str) or \
700
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
701
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
702
                                   description='API.INVALID_END_TIME_OF_DAY')
703
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
704
705
        power_value = None
706
        if 'power_value' in new_values['data'].keys():
707
            if new_values['data']['power_value'] is not None and \
708
                    (isinstance(new_values['data']['power_value'], int) or
709
                     isinstance(new_values['data']['power_value'], float)):
710
                power_value = str.strip(new_values['data']['power_value'])
711
712
        power_point_id = None
713
        if 'power_point_id' in new_values['data'].keys():
714
            if new_values['data']['power_point_id'] is not None and \
715
                    new_values['data']['power_point_id'] <= 0:
716
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
717
                                       description='API.INVALID_POWER_POINT_ID')
718
            power_point_id = new_values['data']['power_point_id']
719
720
        power_equation = None
721
        if 'power_equation' in new_values['data'].keys():
722
            if new_values['data']['power_equation'] is not None and \
723
                    isinstance(new_values['data']['power_equation'], str) and \
724
                    len(str.strip(new_values['data']['power_equation'])) > 0:
725
                power_equation = str.strip(new_values['data']['power_equation'])
726
727
        description = None
728
        if 'description' in new_values['data'].keys():
729
            if new_values['data']['description'] is not None and \
730
                    isinstance(new_values['data']['description'], str) and \
731
                    len(str.strip(new_values['data']['description'])) > 0:
732
                description = str.strip(new_values['data']['description'])
733
734
        cnx = mysql.connector.connect(**config.myems_system_db)
735
        cursor = cnx.cursor()
736
        cursor.execute(" SELECT name "
737
                       " FROM tbl_control_modes "
738
                       " WHERE id = %s ", (id_,))
739
        if cursor.fetchone() is None:
740
            cursor.close()
741
            cnx.close()
742
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.NOT_FOUND',
743
                                   description='API.CONTROL_MODE_NOT_FOUND')
744
745
        add_values = (" INSERT INTO tbl_control_modes_times "
746
                      "    (control_mode_id, start_time_of_day, end_time_of_day, power_value, "
747
                      "     power_point_id, power_equation, description) "
748
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
749
        cursor.execute(add_values, (id_,
750
                                    start_time_of_day,
751
                                    end_time_of_day,
752
                                    power_value,
753
                                    power_point_id,
754
                                    power_equation,
755
                                    description))
756
        new_id = cursor.lastrowid
757
        cnx.commit()
758
        cursor.close()
759
        cnx.close()
760
761
        resp.status = falcon.HTTP_201
762
        resp.location = '/controlmodes/' + str(id_) + 'times/' + str(new_id)
763
764
765
class ControlModeTimeItem:
766
    @staticmethod
767
    @user_logger
768
    def __init__():
769
        """Initializes"""
770
        pass
771
772
    @staticmethod
773
    def on_options(req, resp, id_, tid):
774
        _ = req
775
        resp.status = falcon.HTTP_200
776
        _ = id_
777
778
    @staticmethod
779
    def on_get(req, resp, id_, tid):
780
        if 'API-KEY' not in req.headers or \
781
                not isinstance(req.headers['API-KEY'], str) or \
782
                len(str.strip(req.headers['API-KEY'])) == 0:
783
            access_control(req)
784
        else:
785
            api_key_control(req)
786
        if not id_.isdigit() or int(id_) <= 0:
787
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
788
                                   description='API.INVALID_CONTROL_MODE_ID')
789
790
        if not tid.isdigit() or int(tid) <= 0:
791
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
792
                                   description='API.INVALID_CONTROL_MODE_TIME_ID')
793
794
        cnx = mysql.connector.connect(**config.myems_system_db)
795
        cursor = cnx.cursor()
796
797
        query = (" SELECT id, name "
798
                 " FROM tbl_points ")
799
        cursor.execute(query)
800
        rows_points = cursor.fetchall()
801
802
        point_dict = dict()
803
        if rows_points is not None and len(rows_points) > 0:
804
            for row in rows_points:
805
                point_dict[row[0]] = {"id": row[0],
806
                                      "name": row[1]}
807
808
        query = (" SELECT id, control_mode_id, start_time_of_day, end_time_of_day, "
809
                 "        power_value, power_point_id, power_equation, description "
810
                 " FROM tbl_control_modes_times "
811
                 " WHERE control_mode_id = %s AND id = %s ")
812
        cursor.execute(query, (id_, tid))
813
        row_time = cursor.fetchone()
814
        cursor.close()
815
        cnx.close()
816
817
        if row_time is None:
818
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
819
                                   description='API.CONTROL_MODE_TIME_NOT_FOUND_OR_NOT_MATCH')
820
        else:
821
            start_time_of_day = str(row_time[2])
822
            parts = start_time_of_day.split(':')
823
            hour = parts[0].zfill(2)
824
            minute = parts[1].zfill(2) if len(parts) > 1 else '00'
825
            second = parts[2].zfill(2) if len(parts) > 2 else '00'
826
            start_time_of_day = f"{hour}:{minute}:{second}"
827
828
            end_time_of_day = str(row_time[3])
829
            parts = end_time_of_day.split(':')
830
            hour = parts[0].zfill(2)
831
            minute = parts[1].zfill(2) if len(parts) > 1 else '00'
832
            second = parts[2].zfill(2) if len(parts) > 2 else '00'
833
            end_time_of_day = f"{hour}:{minute}:{second}"
834
835
            meta_result = {"id": row_time[0],
836
                           "control_mode_id": row_time[1],
837
                           "start_time_of_day": start_time_of_day,
838
                           "end_time_of_day": end_time_of_day,
839
                           "power_value": row_time[4],
840
                           "power_point": point_dict.get(row_time[5], None),
841
                           "power_equation": row_time[6],
842
                           "description": row_time[7]}
843
844
        resp.text = json.dumps(meta_result)
845
846
    @staticmethod
847
    @user_logger
848
    def on_delete(req, resp, id_, tid):
849
        admin_control(req)
850
        if not id_.isdigit() or int(id_) <= 0:
851
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
852
                                   description='API.INVALID_CONTROL_MODE_ID')
853
854
        if not tid.isdigit() or int(tid) <= 0:
855
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
856
                                   description='API.INVALID_CONTROL_MODE_TIME_ID')
857
858
        cnx = mysql.connector.connect(**config.myems_system_db)
859
        cursor = cnx.cursor()
860
861
        cursor.execute(" SELECT id "
862
                       " FROM tbl_control_modes "
863
                       " WHERE id = %s ",
864
                       (id_,))
865
        row = cursor.fetchone()
866
        if row is None:
867
            cursor.close()
868
            cnx.close()
869
            raise falcon.HTTPError(status=falcon.HTTP_400,
870
                                   title='API.NOT_FOUND',
871
                                   description='API.CONTROL_MODE_NOT_FOUND')
872
873
        cursor.execute(" SELECT name "
874
                       " FROM tbl_control_modes_times "
875
                       " WHERE control_mode_id = %s AND id = %s ",
876
                       (id_, tid,))
877
        row = cursor.fetchone()
878
        if row is None:
879
            cursor.close()
880
            cnx.close()
881
            raise falcon.HTTPError(status=falcon.HTTP_400,
882
                                   title='API.NOT_FOUND',
883
                                   description='API.CONTROL_MODE_TIME_NOT_FOUND_OR_NOT_MATCH')
884
885
        cursor.execute(" DELETE FROM tbl_control_modes_times "
886
                       " WHERE id = %s ", (tid,))
887
        cnx.commit()
888
889
        cursor.close()
890
        cnx.close()
891
892
        resp.status = falcon.HTTP_204
893
894
    @staticmethod
895
    @user_logger
896
    def on_put(req, resp, id_, tid):
897
        """Handles PUT requests"""
898
        admin_control(req)
899
        if not id_.isdigit() or int(id_) <= 0:
900
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
901
                                   description='API.INVALID_CONTROL_MODE_ID')
902
903
        if not tid.isdigit() or int(tid) <= 0:
904
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
905
                                   description='API.INVALID_CONTROL_MODE_TIME_ID')
906
907
        try:
908
            raw_json = req.stream.read().decode('utf-8')
909
        except Exception as ex:
910
            print(str(ex))
911
            raise falcon.HTTPError(status=falcon.HTTP_400,
912
                                   title='API.BAD_REQUEST',
913
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
914
915
        new_values = json.loads(raw_json)
916
917
        if 'start_time_of_day' not in new_values['data'].keys() or \
918
                not isinstance(new_values['data']['start_time_of_day'], str) or \
919
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
920
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
921
                                   description='API.INVALID_START_TIME_OF_DAY')
922
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
923
924
        if 'end_time_of_day' not in new_values['data'].keys() or \
925
                not isinstance(new_values['data']['end_time_of_day'], str) or \
926
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
927
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
928
                                   description='API.INVALID_END_TIME_OF_DAY')
929
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
930
931
        power_value = None
932
        if 'power_value' in new_values['data'].keys():
933
            if new_values['data']['power_value'] is not None and \
934
                    (isinstance(new_values['data']['power_value'], int) or
935
                     isinstance(new_values['data']['power_value'], float)):
936
                power_value = str.strip(new_values['data']['power_value'])
937
938
        power_point_id = None
939
        if 'power_point_id' in new_values['data'].keys():
940
            if new_values['data']['power_point_id'] is not None and \
941
                    new_values['data']['power_point_id'] <= 0:
942
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
943
                                       description='API.INVALID_POWER_POINT_ID')
944
            power_point_id = new_values['data']['power_point_id']
945
946
        power_equation = None
947
        if 'power_equation' in new_values['data'].keys():
948
            if new_values['data']['power_equation'] is not None and \
949
                    isinstance(new_values['data']['power_equation'], str) and \
950
                    len(str.strip(new_values['data']['power_equation'])) > 0:
951
                power_equation = str.strip(new_values['data']['power_equation'])
952
953
        description = None
954
        if 'description' in new_values['data'].keys():
955
            if new_values['data']['description'] is not None and \
956
                    isinstance(new_values['data']['description'], str) and \
957
                    len(str.strip(new_values['data']['description'])) > 0:
958
                description = str.strip(new_values['data']['description'])
959
960
        cnx = mysql.connector.connect(**config.myems_system_db)
961
        cursor = cnx.cursor()
962
963
        cursor.execute(" SELECT name "
964
                       " FROM tbl_control_modes "
965
                       " WHERE id = %s ", (id_,))
966
        if cursor.fetchone() is None:
967
            cursor.close()
968
            cnx.close()
969
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.NOT_FOUND',
970
                                   description='API.CONTROL_MODE_NOT_FOUND')
971
972
        cursor.execute(" SELECT id "
973
                       " FROM tbl_control_modes_times "
974
                       " WHERE control_mode_id = %s AND id = %s ",
975
                       (id_, tid,))
976
        row = cursor.fetchone()
977
        if row is None:
978
            cursor.close()
979
            cnx.close()
980
            raise falcon.HTTPError(status=falcon.HTTP_400,
981
                                   title='API.NOT_FOUND',
982
                                   description='API.CONTROL_MODE_TIME_NOT_FOUND_OR_NOT_MATCH')
983
984
        add_values = (" UPDATE tbl_control_modes_times "
985
                      " SET start_time_of_day = %s , end_time_of_day = %s, power_value = %s, "
986
                      "     power_point_id = %s, power_equation = %s, description = %s "
987
                      " WHERE id = %s ")
988
        cursor.execute(add_values, (start_time_of_day,
989
                                    end_time_of_day,
990
                                    power_value,
991
                                    power_point_id,
992
                                    power_equation,
993
                                    description,
994
                                    tid))
995
        cnx.commit()
996
997
        cursor.close()
998
        cnx.close()
999
1000
        resp.status = falcon.HTTP_200
1001