Django+DRF发送验码的实现

先安装SDK,执行命令:pip install alibabacloud_dysmsapi20170525==2.0.24

1.根据阿里文档定义一个发送验证码的类方便调用

from alibabacloud_dysmsapi20170525.client import Client
from alibabacloud_tea_openapi.models import Config
from alibabacloud_dysmsapi20170525.models import SendSmsRequest
from alibabacloud_tea_util.models import RuntimeOptions
import json


class Send_SMS():
    access_key_id = 'xxxxxxxxxxxxxxx'
    access_key_secret = 'xxxxxxxxxxxx'
    endpoint = 'dysmsapi.aliyuncs.com'
    sign_name = '阿里云短信测试'
    template_code = 'SMS_154950909'

    def __init__(self):
        self.config = Config(
            # 必填,您的 AccessKey ID,
            access_key_id=self.access_key_id,
            # 必填,您的 AccessKey Secret,
            access_key_secret=self.access_key_secret,
            endpoint=self.endpoint
        )

    def send(self, mobile: str, code: str):
        """
        mobile: 手机号
        code:验证码
        """
        # 1. 创建一个客服端
        client = Client(self.config)
        send_sms_request = SendSmsRequest(
            phone_numbers=mobile,
            template_param=json.dumps({"code": code}),
            sign_name=self.sign_name,
            template_code=self.template_code,

        )
        # 2. 创建短信对象
        # 3. 设置允许时间选项
        runtime = RuntimeOptions()
        #
        try:
            # 4. 发送短信
            res = client.send_sms_with_options(send_sms_request, runtime)
            if res.body.code == 'OK':
                return {'code': "OK", "message": "短信发送成功!"}
            else:
                return {'code': "NO", "error": res.body.message}
        except Exception as e:
            return {'code': "NO", "message": "短信发送失败!"}

2.视图类的实现

class SendSMSView(APIView):
    """ 发送短信 """

    def post(self, request):
        mobile = request.data.get('mobile')
        res = re.match(r'^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$', mobile)
        if not res:
            return Response({"error": "无效的手机号"}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        else:
            # 1. 生成一个随机的验证码
            code = self.get_random_code()
            # 2. 发送短信
            res_info = Send_SMS().send(mobile=mobile, code=code)
            if res_info['code'] == 'OK':
                # 将短信验证码入库
                vcode = VerifCode.objects.create(mobile=mobile,code=code)
                res_info['codeID'] = vcode.id
                return Response(res_info, status=status.HTTP_200_OK)
            else:
                return Response(res_info, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def get_random_code(self):
        """ 随机生成6位数的验证码 """
        code = ''.join([random.choice(string.digits) for _ in range(6)])
        return code

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值