| Conditions | 35 |
| Total Lines | 152 |
| Code Lines | 123 |
| Lines | 35 |
| Ratio | 23.03 % |
| Changes | 0 | ||
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:
If many parameters/temporary variables are present:
Complex classes like core.wechatmessage.WechatMessageCollection.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 re |
||
| 94 | @staticmethod |
||
| 95 | @user_logger |
||
| 96 | def on_post(req, resp): |
||
| 97 | """Handles POST requests""" |
||
| 98 | access_control(req) |
||
| 99 | |||
| 100 | try: |
||
| 101 | raw_json = req.stream.read().decode('utf-8') |
||
| 102 | except Exception as ex: |
||
| 103 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) |
||
| 104 | |||
| 105 | new_values = json.loads(raw_json) |
||
| 106 | |||
| 107 | if 'rule_id' in new_values['data'].keys(): |
||
| 108 | if new_values['data']['rule_id'] <= 0: |
||
| 109 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 110 | description='API.INVALID_RULE_ID') |
||
| 111 | rule_id = new_values['data']['rule_id'] |
||
| 112 | else: |
||
| 113 | rule_id = None |
||
| 114 | |||
| 115 | if 'recipient_name' not in new_values['data'].keys() or \ |
||
| 116 | not isinstance(new_values['data']['recipient_name'], str) or \ |
||
| 117 | len(str.strip(new_values['data']['recipient_name'])) == 0: |
||
| 118 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 119 | description='API.INVALID_RECIPIENT_NAME') |
||
| 120 | recipient_name = str.strip(new_values['data']['recipient_name']) |
||
| 121 | |||
| 122 | if 'recipient_openid' not in new_values['data'].keys() or \ |
||
| 123 | not isinstance(new_values['data']['recipient_openid'], str) or \ |
||
| 124 | len(str.strip(new_values['data']['recipient_openid'])) == 0: |
||
| 125 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 126 | description='API.INVALID_RECIPIENT_OPENID') |
||
| 127 | recipient_openid = str.strip(new_values['data']['recipient_openid']) |
||
| 128 | match = re.match(r'^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z-_]{28}$', recipient_openid) |
||
| 129 | if match is None: |
||
| 130 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 131 | description='API.INVALID_OPENID') |
||
| 132 | |||
| 133 | if 'message_template_id' not in new_values['data'].keys() or \ |
||
| 134 | not isinstance(new_values['data']['message_template_id'], str) or \ |
||
| 135 | len(str.strip(new_values['data']['message_template_id'])) == 0: |
||
| 136 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 137 | description='API.INVALID_MESSAGE_TEMPLATE_ID') |
||
| 138 | message_template_id = str.strip(new_values['data']['message_template_id']) |
||
| 139 | match = re.match(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]{43}$', message_template_id) |
||
| 140 | if match is None: |
||
| 141 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 142 | description='API.INVALID_MESSAGE_TEMPLATE_ID') |
||
| 143 | |||
| 144 | if 'message_data' not in new_values['data'].keys() or \ |
||
| 145 | not isinstance(new_values['data']['message_data'], str) or \ |
||
| 146 | len(str.strip(new_values['data']['message_data'])) == 0: |
||
| 147 | raise falcon.HTTPError(falcon.HTTP_400, |
||
| 148 | title='API.BAD_REQUEST', |
||
| 149 | description='API.INVALID_MESSAGE_DATA') |
||
| 150 | message_data = str.strip(new_values['data']['message_data']) |
||
| 151 | # validate expression in json |
||
| 152 | try: |
||
| 153 | json.loads(message_data) |
||
| 154 | except Exception as ex: |
||
| 155 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description=ex) |
||
| 156 | |||
| 157 | if 'acknowledge_code' not in new_values['data'].keys() or \ |
||
| 158 | not isinstance(new_values['data']['acknowledge_code'], str) or \ |
||
| 159 | len(str.strip(new_values['data']['acknowledge_code'])) == 0: |
||
| 160 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 161 | description='API.INVALID_ACKNOWLEDGE_CODE') |
||
| 162 | acknowledge_code = str.strip(new_values['data']['acknowledge_code']) |
||
| 163 | |||
| 164 | if 'created_datetime' not in new_values['data'].keys() or \ |
||
| 165 | not isinstance(new_values['data']['created_datetime'], str) or \ |
||
| 166 | len(str.strip(new_values['data']['created_datetime'])) == 0: |
||
| 167 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 168 | description='API.INVALID_CREATED_DATETIME') |
||
| 169 | created_datetime_local = str.strip(new_values['data']['created_datetime']) |
||
| 170 | |||
| 171 | if 'scheduled_datetime' not in new_values['data'].keys() or \ |
||
| 172 | not isinstance(new_values['data']['scheduled_datetime'], str) or \ |
||
| 173 | len(str.strip(new_values['data']['scheduled_datetime'])) == 0: |
||
| 174 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 175 | description='API.INVALID_SCHEDULED_DATETIME') |
||
| 176 | scheduled_datetime_local = str.strip(new_values['data']['scheduled_datetime']) |
||
| 177 | |||
| 178 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
| 179 | if config.utc_offset[0] == '-': |
||
| 180 | timezone_offset = -timezone_offset |
||
| 181 | |||
| 182 | View Code Duplication | if created_datetime_local is None: |
|
| 183 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 184 | description="API.INVALID_CREATED_DATETIME") |
||
| 185 | else: |
||
| 186 | created_datetime_local = str.strip(created_datetime_local) |
||
| 187 | try: |
||
| 188 | created_datetime_utc = datetime.strptime(created_datetime_local, |
||
| 189 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
| 190 | timedelta(minutes=timezone_offset) |
||
| 191 | except ValueError: |
||
| 192 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 193 | description="API.INVALID_CREATED_DATETIME") |
||
| 194 | |||
| 195 | View Code Duplication | if scheduled_datetime_local is None: |
|
| 196 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 197 | description="API.INVALID_SCHEDULED_DATETIME") |
||
| 198 | else: |
||
| 199 | scheduled_datetime_local = str.strip(scheduled_datetime_local) |
||
| 200 | try: |
||
| 201 | scheduled_datetime_utc = datetime.strptime(scheduled_datetime_local, |
||
| 202 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
| 203 | timedelta(minutes=timezone_offset) |
||
| 204 | except ValueError: |
||
| 205 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 206 | description="API.INVALID_SCHEDULED_DATETIME") |
||
| 207 | |||
| 208 | status = 'new' |
||
| 209 | |||
| 210 | cnx = mysql.connector.connect(**config.myems_fdd_db) |
||
| 211 | cursor = cnx.cursor() |
||
| 212 | |||
| 213 | View Code Duplication | if rule_id is not None: |
|
| 214 | cursor.execute(" SELECT name " |
||
| 215 | " FROM tbl_rules " |
||
| 216 | " WHERE id = %s ", |
||
| 217 | (new_values['data']['rule_id'],)) |
||
| 218 | row = cursor.fetchone() |
||
| 219 | if row is None: |
||
| 220 | cursor.close() |
||
| 221 | cnx.disconnect() |
||
| 222 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 223 | description='API.RULE_NOT_FOUND') |
||
| 224 | |||
| 225 | add_row = (" INSERT INTO tbl_wechat_messages_outbox" |
||
| 226 | " (rule_id, recipient_name, recipient_openid, message_template_id, message_data," |
||
| 227 | " acknowledge_code, created_datetime_utc, scheduled_datetime_utc, status) " |
||
| 228 | " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ") |
||
| 229 | |||
| 230 | cursor.execute(add_row, (rule_id, |
||
| 231 | recipient_name, |
||
| 232 | recipient_openid, |
||
| 233 | message_template_id, |
||
| 234 | message_data, |
||
| 235 | acknowledge_code, |
||
| 236 | created_datetime_utc, |
||
| 237 | scheduled_datetime_utc, |
||
| 238 | status)) |
||
| 239 | new_id = cursor.lastrowid |
||
| 240 | cnx.commit() |
||
| 241 | cursor.close() |
||
| 242 | cnx.disconnect() |
||
| 243 | |||
| 244 | resp.status = falcon.HTTP_201 |
||
| 245 | resp.location = '/wechatmessages/' + str(new_id) |
||
| 246 | |||
| 330 |