天天看點

手機短信驗證

手機驗證接口

from rest_framework.views import APIView
from .models import User
from utils.response import APIResponse
import re
# 注冊邏輯:1.校驗手機号是否存在 2.發送驗證碼 3.完成注冊
class MobileAPIView(APIView):
    def post(self, request, *args, **kwargs):
        mobile = request.data.get(\'mobile\')
        if not mobile or not re.match(r\'^1[3-9]\d{9}$\', mobile):
            return APIResponse(1, \'資料有誤\')
        try:
            User.objects.get(mobile=mobile)
            return APIResponse(2, \'已注冊\')
        except:
            return APIResponse(0, \'未注冊\')      

 發送短信接口

# 發送驗證碼接口分析
from libs import txsms
from django.core.cache import cache
class SMSAPIView(APIView):
    def post(self, request, *args, **kwargs):
        # 1)拿到前台的手機号
        mobile = request.data.get(\'mobile\')
        if not mobile or not re.match(r\'^1[3-9]\d{9}$\', mobile):
            return APIResponse(2, \'資料有誤\')
        # 2)調用txsms生成手機驗證碼
        code = txsms.get_code()
        # 3)調用txsms發送手機驗證碼
        result = txsms.send_sms(mobile, code, 5)
        # 4)失敗回報資訊給前台
        if not result:
            return APIResponse(1, \'短信發送失敗\')
        # 5)成功伺服器緩存手機驗證碼 - 用緩存存儲(友善管理) - redis
        cache.set(\'sms_%s\' % mobile, code, 5 * 60)
        # 6)回報成功資訊給前台
        return APIResponse(0, \'短信發送成功\')      
手機短信驗證