Passed
Push — master ( c6068e...54bd3b )
by Guangyu
02:21 queued 10s
created

emailmessage.EmailMessageCollection.on_get()   F

Complexity

Conditions 14

Size

Total Lines 70
Code Lines 56

Duplication

Lines 70
Ratio 100 %

Importance

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

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 emailmessage.EmailMessageCollection.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 json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
7
8 View Code Duplication
class EmailMessageCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
9
    @staticmethod
10
    def __init__():
11
        pass
12
13
    @staticmethod
14
    def on_options(req, resp, startdate, enddate):
15
        resp.status = falcon.HTTP_200
16
17
    @staticmethod
18
    def on_get(req, resp, startdate, enddate):
19
        try:
20
            start_datetime_local = datetime.strptime(startdate, '%Y-%m-%d')
21
        except Exception:
22
            raise falcon.HTTPError(falcon.HTTP_400,
23
                                   title='API.BAD_REQUEST',
24
                                   description='API.INVALID_START_DATE_FORMAT')
25
        try:
26
            end_datetime_local = datetime.strptime(enddate, '%Y-%m-%d')
27
        except Exception:
28
            raise falcon.HTTPError(falcon.HTTP_400,
29
                                   title='API.BAD_REQUEST',
30
                                   description='API.INVALID_END_DATE_FORMAT')
31
32
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
33
        if config.utc_offset[0] == '-':
34
            timezone_offset = -timezone_offset
35
36
        start_datetime_utc = start_datetime_local.replace(tzinfo=timezone.utc)
37
        start_datetime_utc -= timedelta(minutes=timezone_offset)
38
39
        end_datetime_utc = end_datetime_local.replace(tzinfo=timezone.utc)
40
        end_datetime_utc -= timedelta(minutes=timezone_offset)
41
        end_datetime_utc += timedelta(days=1)
42
43
        if start_datetime_utc >= end_datetime_utc:
44
            raise falcon.HTTPError(falcon.HTTP_400,
45
                                   title='API.BAD_REQUEST',
46
                                   description='API.START_DATETIME_SHOULD_BE_EARLY_THAN_END_DATETIME')
47
48
        try:
49
            cnx = mysql.connector.connect(**config.myems_fdd_db)
50
            cursor = cnx.cursor()
51
        except Exception as e:
52
            raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
53
54
        try:
55
            query = (" SELECT id, recipient_name, recipient_email, "
56
                     "        subject, message, attachment_file_name, "
57
                     "        created_datetime_utc, scheduled_datetime_utc, status "
58
                     " FROM tbl_email_messages "
59
                     " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
60
                     " ORDER BY created_datetime_utc ")
61
            cursor.execute(query, (start_datetime_utc, end_datetime_utc))
62
            rows = cursor.fetchall()
63
64
            if cursor:
65
                cursor.close()
66
            if cnx:
67
                cnx.disconnect()
68
        except Exception as e:
69
            raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
70
71
        result = list()
72
        if rows is not None and len(rows) > 0:
73
            for row in rows:
74
                meta_result = {"id": row[0],
75
                               "recipient_name": row[1],
76
                               "recipient_email": row[2],
77
                               "subject": row[3],
78
                               "message": row[4].replace("<br>", ""),
79
                               "attachment_file_name": row[5],
80
                               "created_datetime": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
81
                               "scheduled_datetime":
82
                                   row[7].timestamp() * 1000 if isinstance(row[7], datetime) else None,
83
                               "status": row[8]}
84
                result.append(meta_result)
85
86
        resp.body = json.dumps(result)
87
88
89 View Code Duplication
class EmailMessageItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
90
    @staticmethod
91
    def __init__():
92
        pass
93
94
    @staticmethod
95
    def on_options(req, resp, id_):
96
        resp.status = falcon.HTTP_200
97
98
    @staticmethod
99
    def on_get(req, resp, id_):
100
        if not id_.isdigit() or int(id_) <= 0:
101
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
102
                                   description='API.INVALID_EMAIL_MESSAGE_ID')
103
104
        try:
105
            cnx = mysql.connector.connect(**config.myems_fdd_db)
106
            cursor = cnx.cursor()
107
        except Exception as e:
108
            raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
109
110
        try:
111
            query = (" SELECT id, recipient_name, recipient_email, "
112
                     "        subject, message, attachment_file_name, "
113
                     "        created_datetime_utc, scheduled_datetime_utc, status "
114
                     " FROM tbl_email_messages "
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
        except Exception as e:
124
            if cursor:
125
                cursor.close()
126
            if cnx:
127
                cnx.disconnect()
128
            raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
129
130
        if row is None:
131
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
132
                                   description='API.EMAIL_MESSAGE_NOT_FOUND')
133
134
        result = {"id": row[0],
135
                  "recipient_name": row[1],
136
                  "recipient_email": row[2],
137
                  "subject": row[3],
138
                  "message": row[4].replace("<br>", ""),
139
                  "attachment_file_name": row[5],
140
                  "created_datetime": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
141
                  "scheduled_datetime": row[7].timestamp() * 1000 if isinstance(row[7], datetime) else None,
142
                  "status": row[8]}
143
144
        resp.body = json.dumps(result)
145
146
    @staticmethod
147
    def on_delete(req, resp, id_):
148
        if not id_.isdigit() or int(id_) <= 0:
149
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
150
                                   description='API.INVALID_EMAIL_MESSAGE_ID')
151
152
        cnx = None
153
        cursor = None
154
        try:
155
            cnx = mysql.connector.connect(**config.myems_fdd_db)
156
            cursor = cnx.cursor()
157
        except Exception as e:
158
            if cursor:
159
                cursor.close()
160
            if cnx:
161
                cnx.disconnect()
162
            raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
163
164
        try:
165
            cursor.execute(" SELECT id FROM tbl_email_messages WHERE id = %s ", (id_,))
166
            row = cursor.fetchone()
167
        except Exception as e:
168
            if cursor:
169
                cursor.close()
170
            if cnx:
171
                cnx.disconnect()
172
            raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
173
174
        if row is None:
175
            if cursor:
176
                cursor.close()
177
            if cnx:
178
                cnx.disconnect()
179
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
180
                                   description='API.EMAIL_MESSAGE_NOT_FOUND')
181
182
        try:
183
            cursor.execute(" DELETE FROM tbl_email_messages WHERE id = %s ", (id_,))
184
            cnx.commit()
185
            if cursor:
186
                cursor.close()
187
            if cnx:
188
                cnx.disconnect()
189
        except Exception as e:
190
            if cursor:
191
                cursor.close()
192
            if cnx:
193
                cnx.disconnect()
194
            raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
195
196
        resp.status = falcon.HTTP_204
197
198