Passed
Push — master ( 4d64ec...79497c )
by Guangyu
07:22 queued 11s
created

core.aliyunsmsapi   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 269
Duplicated Lines 9.67 %

Importance

Changes 0
Metric Value
wmc 55
eloc 207
dl 26
loc 269
rs 6
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A AliyunSMSAPICollection.on_get() 0 24 4
A AliyunSMSAPIItem.on_get() 0 25 4
F AliyunSMSAPIItem.on_put() 0 88 21
F AliyunSMSAPICollection.on_post() 0 73 18
A AliyunSMSAPIItem.on_options() 0 3 1
A AliyunSMSAPIItem.__init__() 0 4 1
A AliyunSMSAPICollection.__init__() 0 4 1
A AliyunSMSAPIItem.on_delete() 26 26 4
A AliyunSMSAPICollection.on_options() 0 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like core.aliyunsmsapi 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 core.userlogger import user_logger
6
7
8
class AliyunSMSAPICollection:
9
    @staticmethod
10
    def __init__():
11
        """Initializes AliyunSMSAPICollection"""
12
        pass
13
14
    @staticmethod
15
    def on_options(req, resp):
16
        resp.status = falcon.HTTP_200
17
18
    @staticmethod
19
    def on_get(req, resp):
20
        cnx = mysql.connector.connect(**config.myems_fdd_db)
21
        cursor = cnx.cursor()
22
23
        query = (" SELECT id, access_key_id, access_key_secret, endpoint, sign_name, template_code "
24
                 " FROM tbl_aliyun_sms_api ")
25
        cursor.execute(query)
26
        rows = cursor.fetchall()
27
        cursor.close()
28
        cnx.disconnect()
29
30
        result = list()
31
        if rows is not None and len(rows) > 0:
32
            for row in rows:
33
                meta_result = {"id": row[0],
34
                               "access_key_id": row[1],
35
                               "access_key_secret": row[2],
36
                               "endpoint": row[3],
37
                               "sign_name": row[4],
38
                               "template_code": row[5]}
39
                result.append(meta_result)
40
41
        resp.body = json.dumps(result)
42
43
    @staticmethod
44
    @user_logger
45
    def on_post(req, resp):
46
        """Handles POST requests"""
47
        try:
48
            raw_json = req.stream.read().decode('utf-8')
49
        except Exception as ex:
50
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
51
52
        new_values = json.loads(raw_json)
53
54
        if 'access_key_id' not in new_values['data'].keys() or \
55
                not isinstance(new_values['data']['access_key_id'], str) or \
56
                len(str.strip(new_values['data']['access_key_id'])) == 0:
57
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
58
                                   description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_ID')
59
        access_key_id = str.strip(new_values['data']['access_key_id'])
60
61
        if 'access_key_secret' not in new_values['data'].keys() or \
62
                not isinstance(new_values['data']['access_key_secret'], str) or \
63
                len(new_values['data']['access_key_secret']) == 0:
64
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
65
                                   description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_SECRET')
66
        access_key_secret = new_values['data']['access_key_secret']
67
68
        if 'endpoint' not in new_values['data'].keys() or \
69
                not isinstance(new_values['data']['endpoint'], str) or \
70
                len(new_values['data']['endpoint']) == 0:
71
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
72
                                   description='API.INVALID_ALIYUN_SMS_API_ENDPOINT')
73
        endpoint = new_values['data']['endpoint']
74
75
        if 'sign_name' not in new_values['data'].keys() or \
76
                not isinstance(new_values['data']['sign_name'], str) or \
77
                len(new_values['data']['sign_name']) == 0:
78
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
79
                                   description='API.INVALID_ALIYUN_SMS_API_SIGN_NAME')
80
        sign_name = new_values['data']['sign_name']
81
82
        if 'template_code' not in new_values['data'].keys() or \
83
                not isinstance(new_values['data']['template_code'], str) or \
84
                len(new_values['data']['template_code']) == 0:
85
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
86
                                   description='API.INVALID_ALIYUN_SMS_API_TEMPLATE_CODE')
87
        template_code = new_values['data']['template_code']
88
89
        cnx = mysql.connector.connect(**config.myems_fdd_db)
90
        cursor = cnx.cursor()
91
92
        cursor.execute(" SELECT id "
93
                       " FROM tbl_aliyun_sms_api "
94
                       " WHERE access_key_id = %s ", (access_key_id,))
95
        if cursor.fetchone() is not None:
96
            cursor.close()
97
            cnx.disconnect()
98
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
99
                                   description='API.ALIYUN_SMS_API_ACCESS_KEY_ID_IS_ALREADY_IN_USE')
100
101
        add_value = (" INSERT INTO tbl_aliyun_sms_api "
102
                     "    (access_key_id, access_key_secret, endpoint, sign_name, template_code) "
103
                     " VALUES (%s, %s, %s, %s, %s) ")
104
        cursor.execute(add_value, (access_key_id,
105
                                   access_key_secret,
106
                                   endpoint,
107
                                   sign_name,
108
                                   template_code))
109
        new_id = cursor.lastrowid
110
        cnx.commit()
111
        cursor.close()
112
        cnx.disconnect()
113
114
        resp.status = falcon.HTTP_201
115
        resp.location = '/aliyunsmsapis/' + str(new_id)
116
117
118
class AliyunSMSAPIItem:
119
    @staticmethod
120
    def __init__():
121
        """Initializes AliyunSMSAPIItem"""
122
        pass
123
124
    @staticmethod
125
    def on_options(req, resp, id_):
126
        resp.status = falcon.HTTP_200
127
128
    @staticmethod
129
    def on_get(req, resp, id_):
130
        if not id_.isdigit() or int(id_) <= 0:
131
            raise falcon.HTTPError(falcon.HTTP_400, '400 Bad Request')
132
133
        cnx = mysql.connector.connect(**config.myems_fdd_db)
134
        cursor = cnx.cursor()
135
136
        query = (" SELECT id, access_key_id, access_key_secret, endpoint, sign_name, template_code "
137
                 " FROM tbl_aliyun_sms_api "
138
                 " WHERE id = %s ")
139
        cursor.execute(query, (id_,))
140
        row = cursor.fetchone()
141
        cursor.close()
142
        cnx.disconnect()
143
        if row is None:
144
            raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND')
145
146
        result = {"id": row[0],
147
                  "access_key_id": row[1],
148
                  "access_key_secret": row[2],
149
                  "endpoint": row[3],
150
                  "sign_name": row[4],
151
                  "template_code": row[5]}
152
        resp.body = json.dumps(result)
153
154 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
155
    @user_logger
156
    def on_delete(req, resp, id_):
157
        if not id_.isdigit() or int(id_) <= 0:
158
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
159
                                   description='API.INVALID_ALIYUN_SMS_API_ID')
160
161
        cnx = mysql.connector.connect(**config.myems_fdd_db)
162
        cursor = cnx.cursor()
163
164
        cursor.execute(" SELECT access_key_id "
165
                       " FROM tbl_aliyun_sms_api "
166
                       " WHERE id = %s ", (id_,))
167
        if cursor.fetchone() is None:
168
            cursor.close()
169
            cnx.disconnect()
170
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
171
                                   description='API.ALIYUN_SMS_API_NOT_FOUND')
172
173
        cursor.execute(" DELETE FROM tbl_aliyun_sms_api WHERE id = %s ", (id_,))
174
        cnx.commit()
175
176
        cursor.close()
177
        cnx.disconnect()
178
179
        resp.status = falcon.HTTP_204
180
181
    @staticmethod
182
    @user_logger
183
    def on_put(req, resp, id_):
184
        """Handles PUT requests"""
185
        try:
186
            raw_json = req.stream.read().decode('utf-8')
187
        except Exception as ex:
188
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
189
190
        if not id_.isdigit() or int(id_) <= 0:
191
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
192
                                   description='API.INVALID_ALIYUN_SMS_API_ID')
193
194
        new_values = json.loads(raw_json)
195
196
        if 'access_key_id' not in new_values['data'].keys() or \
197
                not isinstance(new_values['data']['access_key_id'], str) or \
198
                len(str.strip(new_values['data']['access_key_id'])) == 0:
199
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
200
                                   description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_ID')
201
        access_key_id = str.strip(new_values['data']['access_key_id'])
202
203
        if 'access_key_secret' not in new_values['data'].keys() or \
204
                not isinstance(new_values['data']['access_key_secret'], str) or \
205
                len(new_values['data']['access_key_secret']) == 0:
206
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
207
                                   description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_SECRET')
208
        access_key_secret = new_values['data']['access_key_secret']
209
210
        if 'endpoint' not in new_values['data'].keys() or \
211
                not isinstance(new_values['data']['endpoint'], str) or \
212
                len(new_values['data']['endpoint']) == 0:
213
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
214
                                   description='API.INVALID_ALIYUN_SMS_API_ENDPOINT')
215
        endpoint = new_values['data']['endpoint']
216
217
        if 'sign_name' not in new_values['data'].keys() or \
218
                not isinstance(new_values['data']['sign_name'], str) or \
219
                len(new_values['data']['sign_name']) == 0:
220
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
221
                                   description='API.INVALID_ALIYUN_SMS_API_SIGN_NAME')
222
        sign_name = new_values['data']['sign_name']
223
224
        if 'template_code' not in new_values['data'].keys() or \
225
                not isinstance(new_values['data']['template_code'], str) or \
226
                len(new_values['data']['template_code']) == 0:
227
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
228
                                   description='API.INVALID_ALIYUN_SMS_API_TEMPLATE_CODE')
229
        template_code = new_values['data']['template_code']
230
231
        cnx = mysql.connector.connect(**config.myems_fdd_db)
232
        cursor = cnx.cursor()
233
234
        cursor.execute(" SELECT access_key_id "
235
                       " FROM tbl_aliyun_sms_api "
236
                       " WHERE id = %s ",
237
                       (id_,))
238
        if cursor.fetchone() is None:
239
            cursor.close()
240
            cnx.disconnect()
241
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
242
                                   description='API.ALIYUN_SMS_API_NOT_FOUND')
243
244
        cursor.execute(" SELECT access_key_id "
245
                       " FROM tbl_aliyun_sms_api "
246
                       " WHERE access_key_id = %s AND id != %s ", (access_key_id, id_))
247
        if cursor.fetchone() is not None:
248
            cursor.close()
249
            cnx.disconnect()
250
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
251
                                   description='API.ALIYUN_SMS_API_ACCESS_KEY_ID_IS_ALREADY_IN_USE')
252
253
        update_row = (" UPDATE tbl_aliyun_sms_api "
254
                      " SET access_key_id = %s, access_key_secret = %s, endpoint = %s, sign_name = %s, "
255
                      "     template_code = %s "
256
                      " WHERE id = %s ")
257
        cursor.execute(update_row, (access_key_id,
258
                                    access_key_secret,
259
                                    endpoint,
260
                                    sign_name,
261
                                    template_code,
262
                                    id_,))
263
        cnx.commit()
264
265
        cursor.close()
266
        cnx.disconnect()
267
268
        resp.status = falcon.HTTP_200
269