1禁炒、發(fā)送驗(yàn)證碼模塊
import json
#發(fā)送驗(yàn)證碼
class YuanPian(object):
def __init__(self, api_key):
#個(gè)人在云片網(wǎng)的身份
self.api_key = api_key
#要請(qǐng)求的url ======>>>>>>>>發(fā)短信
self.single_send_url = "https://sms.yunpian.com/v2/sms/single_send.json"
def send_sms(self,code,mobile):
"""
apikey string 是 是 用戶唯一標(biāo)識(shí)焙矛,在管理控制臺(tái)獲取 9b11127a9701975c734b8aee81ee3526
mobile string 是 是 接收的手機(jī)號(hào)超棺,僅支持單號(hào)碼發(fā)送; 15205201314
text string 是 是 已審核短信模板 【云片網(wǎng)】您的驗(yàn)證碼是1234
讓云片網(wǎng)發(fā)送短信驗(yàn)證 我們需要傳參數(shù)
code:短信驗(yàn)證碼
mobile:手機(jī)號(hào)碼
"""
params = {
"apikey":self.api_key,
"moblie":mobile,
"text":"[四方科技]您的驗(yàn)證碼是{}.如過不是本人操作,請(qǐng)忽略此短信".format(code)
}
#發(fā)起一個(gè)網(wǎng)絡(luò)請(qǐng)求,得到響應(yīng)
response = requests.post(self.single_send_url,data=params)
#提示一下
ret = json.loads(response.text)
return ret
if __name__ == '__main__':
#測試
#實(shí)例化一個(gè)對(duì)象
yun_pian = YuanPian("c60770e37f172c235b9b3c0380807108") #參數(shù)云片api_key
yun_pian.send_sms('1314','15836540122') #參數(shù):驗(yàn)證模板养交、手機(jī)號(hào)
2\驗(yàn)證手機(jī)號(hào)模塊:序列化
from LeShop import settings
from rest_framework import serializers
from datetime import datetime,timedelta
#導(dǎo)入用戶模型
from django.contrib.auth import get_user_model
from .models import VerifyCode
User = get_user_model()
#只做驗(yàn)證手機(jī)號(hào)
#發(fā)送驗(yàn)證馬的時(shí)候,她傳手機(jī)號(hào)
class SmsSerializer(serializers.Serializer):
mobile = serializers.CharField(max_length=11,label="手機(jī)號(hào)")
#validate + 字段名字 表示用戶發(fā)mobile會(huì)調(diào)用validate_mobile這個(gè)方法
def validate_mobile(self, mobile):
#驗(yàn)證方法
#1瓢宦、驗(yàn)證是否注冊(cè)
if User.objects.filter(mobile=mobile).count():
raise serializers.ValidationError("用戶已經(jīng)注冊(cè)")
#2碎连、驗(yàn)證號(hào)碼正則表達(dá)式 是否真是
if not re.match(settings.REGEX_MOBILE,mobile):
raise serializers.ValidationError("手機(jī)號(hào)不正確")
#3、判斷頻率一分鐘只能發(fā)一次
one_minutes_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
if VerifyCode.objects.filter(add_time__gt=one_minutes_ago,mobile=mobile):
raise serializers.ValidationError("60秒內(nèi)只能發(fā)送一次")
return mobile
3\視圖模塊
from rest_framework import viewsets
# Create your views here.
from rest_framework import mixins
from .serializers import SmsSerializer
from random import choice
from rest_framework.response import Response
from rest_framework import status
from LeShop import settings
from utils.yuanpian import YuanPian
from .models import VerifyCode
class SmsCodeViewset(mixins.CreateModelMixin,viewsets.GenericViewSet):
serializer_class = SmsSerializer #1\只做驗(yàn)證手機(jī)號(hào) #發(fā)送驗(yàn)證馬的時(shí)候驮履,她傳手機(jī)號(hào)
def generate_code(self):
"""
生成四位數(shù)字的驗(yàn)證碼
"""
seeds = "1234567890"
random_str = []
for i in range(4):
random_str.append(choice(seeds))
return "".join(random_str)
#重寫這個(gè)方法
#1鱼辙、父類做的事情 ,很簡單就存一個(gè)模型到數(shù)據(jù)庫疲吸,添加一個(gè)新的數(shù)據(jù)座每,不滿足需求
#2、我要的事情是在弗雷德基礎(chǔ)上
#2摘悴、發(fā)短西驗(yàn)證碼(隨機(jī)生成數(shù)字)
#4、發(fā)送YunPian 接收返回值 code=0是否成功
#5舰绘、保存這個(gè)驗(yàn)證ma
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data) #獲取序列化的類 驗(yàn)證手機(jī)號(hào) SmsSerializer
serializer.is_valid(raise_exception=True)#驗(yàn)證
#可用的手機(jī)號(hào)
yuan_pian = YuanPian(settings.APIKEY)
#生成驗(yàn)證碼
code = self.generate_code()
#validated_data拿到序列化里面的字段
sms_status = yuan_pian.send_sms(code,mobile=serializer.validated_data["mobile"]) # 調(diào)用yuan_pian.send_sms方法發(fā)送驗(yàn)證碼
if sms_status['code']!=0:
#失敗
return Response(sms_status['msg'],status=status.HTTP_400_BAD_REQUEST)
else:
#成功
VerifyCode(code=code,mobile=serializer.validated_data["mobile"])
return Response(sms_status['msg'],status=status.HTTP_201_CREATED)
self.perform_create(serializer)#保存
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)