django框架中嵌入容联云sdk实现短信发送接口

1.注册容联云账号,主要是为了获取如下参数

添加测试手机号

 

2.关于sdk和用法可参考Demo示例,demo下载在最上面Demo下载

3.在自己的项目中导入需用到的模块

4.更改配置为自己申请的应用配置

 5.编写api接口yd_api/apps/users/views.py

from rest_framework.views import APIView
from rest_framework import status as http_status
from django.conf import settings
from yd_api.settings import constants
from mycelery.sms.yuntongxun.sms import CCP
import logging
log = logging.getLogger()
class SMSAPIView(APIView):
    def get(self, request, mobile):
        """
        短信发送接口
        url:  /users/sms/(?P<mobile>1[3-9]\d{9})/
        """
        # 1. 验证手机号码是否已经注册
        try:
            User.objects.get(mobile=mobile)
            return Response({"message": "当前手机号已经被注册"}, status=http_status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            pass

        # 2. 验证手机号是否在一分钟内曾发送过短信了
        redis_conn = get_redis_connection("sms_code")
        ret = redis_conn.get("mobile_%s" % mobile)
        if ret is not None:
            return Response({"message": "短信发送频繁,请稍后发送"}, status=http_status.HTTP_400_BAD_REQUEST)

        # 3. 生成短信验证码
        sms_code = "%06d" % random.randint(1, 999999)

        # 4. 保存短信验证码
        # redis_conn.setex("键","时间","值")
        # 使用redis提供的事物配合管道[pipeline]操作来保证多条命令要么一起执行,要么一起失败
        # redis的事务控制数据的修改,设置和删除操作,对于获取数据没必要使用事务
        pipe = redis_conn.pipeline()   # 创建一个管道
        pipe.multi()   # 开启事务
        pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
        pipe.setex("mobile_%s" % mobile, constants.SMS_INTERVAL_TIME, '_')
        pipe.execute()   # 执行redis事务

        
        # 5.调用短信sdk,发送短信
        try:
            ccp = CCP()
            ret = ccp.send_template_sms(mobile, [sms_code, constants.SMS_EXPIRE_TIME // 60], constants.SMS_TEMPLATE_ID)
            print(f"ret={ret}")
            if not ret:
                log.error("用户注册短信发送失败!手机号:%s" % mobile)
                return Response({"message": "发送短信失败"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
        except:
            return Response({"message": "发送短信失败"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
        # 6.响应发送短信的结果
        return Response({"message": "发送短信成功"})

6.编写应用路由users/urls.py

from django.urls import path,re_path
from . import views
urlpatterns = [
    re_path(r"sms/(?P<mobile>1[3-9]\d{9})/", views.SMSAPIView.as_view()),  # 手机发送短信接口
]

7.编写总路由yd_api/urls.py

from django.urls import path,include

urlpatterns = [
    path('user/', include("users.urls"))
]

8.在启动项目在前端点击

 9.查看手机验证码,短信发送成功

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值