import datetime import traceback import requests, logging, random, re, json from rest_framework import status from rest_framework.throttling import AnonRateThrottle from rest_framework.views import APIView from django_redis import get_redis_connection from ChaCeRndTrans import settings from ChaCeRndTrans.basic import CCAIResponse from ChaCeRndTrans.code import SERVER_ERROR, BAD # PHONE_NO_BIND, PHONE_IS_BIND, NO_REGISTER_PHONE from rbac.models import UserProfile logger = logging.getLogger('error') msg_redis_code = 'rndMsgCode' # 用户短信验证码缓存标志 def random_str(): _str = '1234567890' return ''.join(random.choice(_str) for i in range(4)) def send_message(phone, template_type): msg_code = random_str() key = msg_redis_code + phone visit_time_key = "dodo_visit_" + phone # 用于控制一段时间后放行短信发送 conn = get_redis_connection('default') visit_key = conn.get(visit_time_key) if visit_key is None: conn.incrby(visit_time_key, 1) else: visit_count = int(conn.get(visit_time_key).decode('utf8')) if visit_count < 10: conn.incrby(visit_time_key, 1) else: # is_ttl = conn.ttl(visit_time_key) # 获取剩余时间,秒 # if is_ttl != -1: # return CCAIResponse(msg="发送短信频繁,请稍后再发送。", status=BAD) conn.expire(visit_time_key, 60) return CCAIResponse(data="发送短信频繁,请稍后再发送。", msg="发送短信频繁,请稍后再发送。", status=BAD) # 验证码 conn.hset(key, 'code', msg_code) conn.expire(key, 300) conn.expire(visit_time_key, 300) # 保证5分钟以后这个键会消失 url = settings.MSG_URL if settings.DEVELOP_DEBUG: url = settings.TEST_MSG_URL # params = '{"name":"szccwl","pwd":"md","address":"bz","phone":"13000000000"}' params = {} params['username'] = 'ccw' params['password'] = 'chacewang123456' params['phone'] = phone params['template_type'] = template_type args = '{"code":"%s"}' % msg_code params['args'] = args headers = { 'Content-Type': 'application/x-www-form-urlencoded' } try: count = 0 flag = False result = {} response = {} while count < 3 and flag is False: response = requests.request("GET", url, headers=headers, data=params) if response.status_code == 200: flag = True else: count = count + 1 if flag is True: result = json.loads(response.text) if 'code' in result.keys() and result['code'] == 200: return CCAIResponse('success') else: return CCAIResponse(data="发送短信失败", msg="发送短信失败!", status=BAD) except Exception as e: logger.error("get MessageView failed: \n%s" % traceback.format_exc()) return CCAIResponse(msg='发送验证码出错', status=SERVER_ERROR) class MessageView(APIView): """ 发送验证码 """ # throttle_classes = (AnonRateThrottle,) def get(self, request, *args, **kwargs): try: params = request.GET phone = params.get('phone') if phone == None or phone == '': return CCAIResponse(data="请输入正确的手机号", msg="手机号不能为空", status=status.HTTP_400_BAD_REQUEST) ret = re.match(r"^1[3-9]\d{9}$", phone) if ret: # return CCAIResponse('success') return send_message(phone, 'Ccw_TemplateType_Captcha') else: return CCAIResponse(data="请输入正确的手机号", msg="请输入正确的手机号", status=status.HTTP_400_BAD_REQUEST) except Exception as e: logger.error("send MessageView failed: \n%s" % traceback.format_exc()) return CCAIResponse(data="发送验证码出错", msg="发送验证码出错", status=SERVER_ERROR)