Conditions | 42 |
Total Lines | 173 |
Code Lines | 138 |
Lines | 35 |
Ratio | 20.23 % |
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.WechatMessageItem.on_put() 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 |
||
297 | @staticmethod |
||
298 | @user_logger |
||
299 | def on_put(req, resp, id_): |
||
300 | """Handles PUT requests""" |
||
301 | access_control(req) |
||
302 | |||
303 | if not id_.isdigit() or int(id_) <= 0: |
||
304 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
305 | description='API.INVALID_TEXT_MESSAGE_ID') |
||
306 | |||
307 | try: |
||
308 | raw_json = req.stream.read().decode('utf-8') |
||
309 | except Exception as ex: |
||
310 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) |
||
311 | |||
312 | new_values = json.loads(raw_json) |
||
313 | |||
314 | if 'rule_id' in new_values['data'].keys(): |
||
315 | if new_values['data']['rule_id'] <= 0: |
||
316 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
317 | description='API.INVALID_RULE_ID') |
||
318 | rule_id = new_values['data']['rule_id'] |
||
319 | else: |
||
320 | rule_id = None |
||
321 | |||
322 | if 'recipient_name' not in new_values['data'].keys() or \ |
||
323 | not isinstance(new_values['data']['recipient_name'], str) or \ |
||
324 | len(str.strip(new_values['data']['recipient_name'])) == 0: |
||
325 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
326 | description='API.INVALID_RECIPIENT_NAME') |
||
327 | recipient_name = str.strip(new_values['data']['recipient_name']) |
||
328 | |||
329 | if 'recipient_openid' not in new_values['data'].keys() or \ |
||
330 | not isinstance(new_values['data']['recipient_openid'], str) or \ |
||
331 | len(str.strip(new_values['data']['recipient_openid'])) == 0: |
||
332 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
333 | description='API.INVALID_RECIPIENT_OPENID') |
||
334 | recipient_openid = str.strip(new_values['data']['recipient_openid']) |
||
335 | match = re.match(r'^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z-_]{28}$', recipient_openid) |
||
336 | if match is None: |
||
337 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
338 | description='API.INVALID_OPENID') |
||
339 | |||
340 | if 'message_template_id' not in new_values['data'].keys() or \ |
||
341 | not isinstance(new_values['data']['message_template_id'], str) or \ |
||
342 | len(str.strip(new_values['data']['message_template_id'])) == 0: |
||
343 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
344 | description='API.INVALID_MESSAGE_TEMPLATE_ID') |
||
345 | message_template_id = str.strip(new_values['data']['message_template_id']) |
||
346 | match = re.match(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]{43}$', message_template_id) |
||
347 | if match is None: |
||
348 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
349 | description='API.INVALID_MESSAGE_TEMPLATE_ID') |
||
350 | |||
351 | if 'message_data' not in new_values['data'].keys() or \ |
||
352 | not isinstance(new_values['data']['message_data'], str) or \ |
||
353 | len(str.strip(new_values['data']['message_data'])) == 0: |
||
354 | raise falcon.HTTPError(falcon.HTTP_400, |
||
355 | title='API.BAD_REQUEST', |
||
356 | description='API.INVALID_MESSAGE_DATA') |
||
357 | message_data = str.strip(new_values['data']['message_data']) |
||
358 | # validate expression in json |
||
359 | try: |
||
360 | json.loads(message_data) |
||
361 | except Exception as ex: |
||
362 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description=ex) |
||
363 | |||
364 | if 'acknowledge_code' not in new_values['data'].keys() or \ |
||
365 | not isinstance(new_values['data']['acknowledge_code'], str) or \ |
||
366 | len(str.strip(new_values['data']['acknowledge_code'])) == 0: |
||
367 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
368 | description='API.INVALID_ACKNOWLEDGE_CODE') |
||
369 | acknowledge_code = str.strip(new_values['data']['acknowledge_code']) |
||
370 | |||
371 | if 'status' not in new_values['data'].keys() or \ |
||
372 | not isinstance(new_values['data']['status'], str) or \ |
||
373 | len(str.strip(new_values['data']['status'])) == 0 or \ |
||
374 | str.strip(new_values['data']['status']) not in ('new', 'acknowledged', 'timeout'): |
||
375 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
376 | description='API.INVALID_STATUS') |
||
377 | status = str.strip(new_values['data']['status']) |
||
378 | |||
379 | if 'created_datetime' not in new_values['data'].keys() or \ |
||
380 | not isinstance(new_values['data']['created_datetime'], str) or \ |
||
381 | len(str.strip(new_values['data']['created_datetime'])) == 0: |
||
382 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
383 | description='API.INVALID_CREATED_DATETIME') |
||
384 | created_datetime_local = str.strip(new_values['data']['created_datetime']) |
||
385 | |||
386 | if 'scheduled_datetime' not in new_values['data'].keys() or \ |
||
387 | not isinstance(new_values['data']['scheduled_datetime'], str) or \ |
||
388 | len(str.strip(new_values['data']['scheduled_datetime'])) == 0: |
||
389 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
390 | description='API.INVALID_SCHEDULED_DATETIME') |
||
391 | scheduled_datetime_local = str.strip(new_values['data']['scheduled_datetime']) |
||
392 | |||
393 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
394 | if config.utc_offset[0] == '-': |
||
395 | timezone_offset = -timezone_offset |
||
396 | |||
397 | View Code Duplication | if created_datetime_local is None: |
|
398 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
399 | description="API.INVALID_CREATED_DATETIME") |
||
400 | else: |
||
401 | created_datetime_local = str.strip(created_datetime_local) |
||
402 | try: |
||
403 | created_datetime_utc = datetime.strptime(created_datetime_local, |
||
404 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
405 | timedelta(minutes=timezone_offset) |
||
406 | except ValueError: |
||
407 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
408 | description="API.INVALID_CREATED_DATETIME") |
||
409 | |||
410 | View Code Duplication | if scheduled_datetime_local is None: |
|
411 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
412 | description="API.INVALID_SCHEDULED_DATETIME") |
||
413 | else: |
||
414 | scheduled_datetime_local = str.strip(scheduled_datetime_local) |
||
415 | try: |
||
416 | scheduled_datetime_utc = datetime.strptime(scheduled_datetime_local, |
||
417 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
418 | timedelta(minutes=timezone_offset) |
||
419 | except ValueError: |
||
420 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
421 | description="API.INVALID_SCHEDULED_DATETIME") |
||
422 | |||
423 | cnx = mysql.connector.connect(**config.myems_fdd_db) |
||
424 | cursor = cnx.cursor() |
||
425 | |||
426 | cursor.execute(" SELECT recipient_name " |
||
427 | " FROM tbl_wechat_messages_outbox " |
||
428 | " WHERE id = %s ", (id_,)) |
||
429 | |||
430 | if cursor.fetchone() is None: |
||
431 | cursor.close() |
||
432 | cnx.disconnect() |
||
433 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
434 | description='API.WECHAT_MESSAGE_NOT_FOUND') |
||
435 | |||
436 | View Code Duplication | if rule_id is not None: |
|
437 | cursor.execute(" SELECT name " |
||
438 | " FROM tbl_rules " |
||
439 | " WHERE id = %s ", |
||
440 | (new_values['data']['rule_id'],)) |
||
441 | row = cursor.fetchone() |
||
442 | if row is None: |
||
443 | cursor.close() |
||
444 | cnx.disconnect() |
||
445 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
446 | description='API.RULE_NOT_FOUND') |
||
447 | |||
448 | update_row = (" UPDATE tbl_wechat_messages_outbox " |
||
449 | " SET rule_id = %s, recipient_name = %s, recipient_openid = %s, message_template_id = %s," |
||
450 | " message_data = %s, acknowledge_code = %s, created_datetime_utc = %s," |
||
451 | " scheduled_datetime_utc = %s, status = %s" |
||
452 | " WHERE id = %s ") |
||
453 | |||
454 | cursor.execute(update_row, (rule_id, |
||
455 | recipient_name, |
||
456 | recipient_openid, |
||
457 | message_template_id, |
||
458 | message_data, |
||
459 | acknowledge_code, |
||
460 | created_datetime_utc, |
||
461 | scheduled_datetime_utc, |
||
462 | status, |
||
463 | id_)) |
||
464 | |||
465 | cnx.commit() |
||
466 | cursor.close() |
||
467 | cnx.disconnect() |
||
468 | |||
469 | resp.status = falcon.HTTP_200 |
||
470 | |||
504 |