Passed
Push — master ( be9b8e...faba06 )
by Guangyu
09:26 queued 12s
created

core.textmessage.TextMessageCollection.on_get()   F

Complexity

Conditions 14

Size

Total Lines 71
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 56
dl 0
loc 71
rs 3.6
c 0
b 0
f 0
cc 14
nop 2

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.textmessage.TextMessageCollection.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 falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
from core.useractivity import user_logger, access_control
7
8
9
class TextMessageCollection:
10
    @staticmethod
11
    def __init__():
12
        """"Initializes TextMessageCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp):
21
        access_control(req)
22
23
        start_datetime_local = req.params.get('startdatetime')
24
        end_datetime_local = req.params.get('enddatetime')
25
26
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
27
        if config.utc_offset[0] == '-':
28
            timezone_offset = -timezone_offset
29
30
        if start_datetime_local is None:
31
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
32
                                   description="API.INVALID_START_DATETIME_FORMAT")
33
        else:
34
            start_datetime_local = str.strip(start_datetime_local)
35
            try:
36
                start_datetime_utc = datetime.strptime(start_datetime_local,
37
                                                       '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
38
                                     timedelta(minutes=timezone_offset)
39
            except ValueError:
40
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
41
                                       description="API.INVALID_START_DATETIME_FORMAT")
42
43
        if end_datetime_local is None:
44
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
45
                                   description="API.INVALID_END_DATETIME_FORMAT")
46
        else:
47
            end_datetime_local = str.strip(end_datetime_local)
48
            try:
49
                end_datetime_utc = datetime.strptime(end_datetime_local,
50
                                                     '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
51
                                   timedelta(minutes=timezone_offset)
52
            except ValueError:
53
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
54
                                       description="API.INVALID_END_DATETIME_FORMAT")
55
56
        if start_datetime_utc >= end_datetime_utc:
57
            raise falcon.HTTPError(falcon.HTTP_400,
58
                                   title='API.BAD_REQUEST',
59
                                   description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
60
        cnx = mysql.connector.connect(**config.myems_fdd_db)
61
        cursor = cnx.cursor()
62
63
        query = (" SELECT id, recipient_name, recipient_mobile, "
64
                 "        message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status "
65
                 " FROM tbl_text_messages_outbox "
66
                 " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
67
                 " ORDER BY created_datetime_utc DESC ")
68
        cursor.execute(query, (start_datetime_utc, end_datetime_utc))
69
        rows = cursor.fetchall()
70
71
        if cursor:
72
            cursor.close()
73
        if cnx:
74
            cnx.disconnect()
75
76
        result = list()
77
        if rows is not None and len(rows) > 0:
78
            for row in rows:
79
                meta_result = {"id": row[0],
80
                               "recipient_name": row[1],
81
                               "recipient_mobile": row[2],
82
                               "message": row[3],
83
                               "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
84
                               "scheduled_datetime": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
85
                               "acknowledge_code": row[6],
86
                               "status": row[7]}
87
                result.append(meta_result)
88
89
        resp.text = json.dumps(result)
90
91
92 View Code Duplication
class TextMessageItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
93
    @staticmethod
94
    def __init__():
95
        """"Initializes TextMessageItem"""
96
        pass
97
98
    @staticmethod
99
    def on_options(req, resp, id_):
100
        resp.status = falcon.HTTP_200
101
102
    @staticmethod
103
    def on_get(req, resp, id_):
104
        access_control(req)
105
        if not id_.isdigit() or int(id_) <= 0:
106
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
107
                                   description='API.INVALID_TEXT_MESSAGE_ID')
108
109
        cnx = mysql.connector.connect(**config.myems_fdd_db)
110
        cursor = cnx.cursor()
111
112
        query = (" SELECT id, recipient_name, recipient_mobile, "
113
                 "        message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status "
114
                 " FROM tbl_text_messages_outbox "
115
                 " WHERE id = %s ")
116
        cursor.execute(query, (id_,))
117
        row = cursor.fetchone()
118
119
        if cursor:
120
            cursor.close()
121
        if cnx:
122
            cnx.disconnect()
123
124
        if row is None:
125
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
126
                                   description='API.TEXT_MESSAGE_NOT_FOUND')
127
128
        result = {"id": row[0],
129
                  "recipient_name": row[1],
130
                  "recipient_mobile": row[2],
131
                  "message": row[3],
132
                  "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
133
                  "scheduled_datetime": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
134
                  "acknowledge_code": row[6],
135
                  "status": row[7]}
136
137
        resp.text = json.dumps(result)
138
139
    @staticmethod
140
    @user_logger
141
    def on_delete(req, resp, id_):
142
        access_control(req)
143
        if not id_.isdigit() or int(id_) <= 0:
144
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
145
                                   description='API.INVALID_TEXT_MESSAGE_ID')
146
147
        cnx = mysql.connector.connect(**config.myems_fdd_db)
148
        cursor = cnx.cursor()
149
150
        cursor.execute(" SELECT id FROM tbl_text_messages_outbox WHERE id = %s ", (id_,))
151
        row = cursor.fetchone()
152
153
        if row is None:
154
            if cursor:
155
                cursor.close()
156
            if cnx:
157
                cnx.disconnect()
158
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
159
                                   description='API.TEXT_MESSAGE_NOT_FOUND')
160
161
        cursor.execute(" DELETE FROM tbl_text_messages_outbox WHERE id = %s ", (id_,))
162
        cnx.commit()
163
164
        if cursor:
165
            cursor.close()
166
        if cnx:
167
            cnx.disconnect()
168
169
        resp.status = falcon.HTTP_204
170