最新要闻

广告

手机

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

家电

【世界播资讯】封装发送短信功能的封装过程

来源:博客园


(资料图)

目录
  • 第一步:在发送短信平台注册账号
  • 第二步:新建一个包具体文件夹目录结构如下
    • 1. init.py代码
    • 1. settings.py代码
    • 2. sms.py代码
  • 第三:写了发送短信的接口
    • 1. 视图类
    • 2. 序列化类
    • 3. 路由

第一步:在发送短信平台注册账号

具体步骤戳这里

第二步:新建一个包具体文件夹目录结构如下

前提条件是要下第三方模块,具体步骤戳这里之后我们开始封装功能

send_sms_v3 包__init__.py  # 导入给外部使用的函数settings.py  # 配置信息sms.py  # 核心:获取n位数字验证码

1. init.py代码

from .sms import get_code, send_sms

1. settings.py代码

点击查看代码
SECRET_ID = "密钥key值"SECRET_KEY = "密钥value值"APP_ID = "APP的id编号"SIGN_NAME = "签名"TEMPLATE_ID = "模板id"

2. sms.py代码

点击查看代码
from tencentcloud.common import credentialfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.sms.v20210111 import sms_client, modelsfrom tencentcloud.common.profile.client_profile import ClientProfilefrom tencentcloud.common.profile.http_profile import HttpProfilefrom . import settingsimport randomimport json# 产生随机验证码的函数def get_code(number=4):    code = ""    for i in range(number):        code += str(random.randint(0, 9))    return code# 发送短信函数def send_sms(code, mobile):    try:        cred = credential.Credential(settings.SECRET_ID, settings.SECRET_KEY)        httpProfile = HttpProfile()        httpProfile.reqMethod = "POST"        httpProfile.reqTimeout = 30        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)        clientProfile = ClientProfile()        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法        clientProfile.language = "en-US"        clientProfile.httpProfile = httpProfile        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)        req = models.SendSmsRequest()        req.SmsSdkAppId = settings.APP_ID        req.SignName = settings.SIGN_NAME        req.TemplateId = settings.TEMPLATE_ID        req.TemplateParamSet = [code, "30"]        req.PhoneNumberSet = ["+86" + mobile,]        req.SessionContext = ""        req.ExtendCode = ""        req.SenderId = ""        resp = client.SendSms(req)        res = json.loads(resp.to_json_string(indent=2))        if res.get("SendStatusSet")[0].get("Code") == "Ok":            return True        else:            return False    except TencentCloudSDKException as err:        print(err)        return False

第三:写了发送短信的接口

1. 视图类

点击查看代码
from libs.send_sms_v3 import get_code, send_sms as send_sms_ssfrom rest_framework.viewsets import GenericViewSetfrom rest_framework.decorators import actionfrom rest_framework.exceptions import APIExceptionfrom common_response import APIResponsefrom .serializer import UserLoginSerializer, UserMobileLoginSerializerfrom .models import Userfrom django.utils.datastructures import MultiValueDictKeyErrorfrom django.core.cache import cachefrom threading import Threadclass UserView(GenericViewSet):    serializer_class = UserLoginSerializer    queryset = User.objects.all().filter(is_active=True)    @action(methods=["GET"], detail=False)    def check_mobile(self, request, *args, **kwargs):        try:            # 从地址栏中取出手机号 query_params : queryDict            mobile = request.query_params["mobile"]            User.objects.get(mobile=mobile)        except MultiValueDictKeyError as e:            raise APIException("手机号格式不对")        except Exception as e:            return APIException        return APIResponse(msg="手机号已存在")    @action(methods=["POST"], detail=False)    def login_mul(self, request, *args, **kwargs):        return self._login(request, *args, **kwargs)    @action(methods=["POST"], detail=False)    def send_sms(self, request):        try:            mobile = request.data["mobile"]            # 生成验证码            code = get_code()            cache.set("sms_code_%s" % mobile, code)            # 使用异步发送短信            t = Thread(target=send_sms_ss, args=[code, mobile])            t.start()            return APIResponse(msg="短信已发送")        except Exception as e:            raise APIException(str(e))    # 重写get_serializer_class方法    def get_serializer_class(self):        if self.action == "login_sms":            return UserMobileLoginSerializer        else:            return super().get_serializer_class()    def _login(self, request, *args, **kwargs):        ser = self.get_serializer(data=request.data)        ser.is_valid(raise_exception=True)        token = ser.context.get("token")        username = ser.context.get("username")        return APIResponse(token=token, username=username)    @action(methods=["POST"], detail=False)    def login_sms(self, request, *args, **kwargs):        return self._login(request)

2. 序列化类

点击查看代码
from .models import Userfrom rest_framework import serializersfrom rest_framework.exceptions import APIExceptionfrom rest_framework_jwt.settings import api_settingsfrom django.core.cache import cacheimport rejwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLERjwt_encode_handler = api_settings.JWT_ENCODE_HANDLERclass BaseUserSerializer():    def validate(self, attrs):        user = self._get_user(attrs)        token = self._get_token(user)        self.context["token"] = token        self.context["username"] = user.username        return attrs    def _get_user(self, attrs):        raise Exception("需要重写该方法")    def _get_token(self, user):        payload = jwt_payload_handler(user)        token = jwt_encode_handler(payload)        return tokenclass UserLoginSerializer(BaseUserSerializer, serializers.ModelSerializer):    # 重写username字段,把原来的校验规则去掉    username = serializers.CharField()    class Meta:        model = User        fields = ["username", "password"]    def _get_user(self, attrs):        username = attrs.get("username")        password = attrs.get("password")        if re.match(r"^1[3-9][0-9]{9}$", username):            user = User.objects.filter(phone=username).first()        elif re.match(r"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$", username):            user = User.objects.filter(email=username).first()        else:            user = User.objects.filter(username=username).first()        if user and user.check_password(password):            return user        else:            raise APIException("用户名不存在或密码错误")class UserMobileLoginSerializer(BaseUserSerializer, serializers.ModelSerializer):    code = serializers.CharField()    mobile = serializers.CharField()    class Meta:        model = User        fields = ["mobile", "code"]    def _get_user(self, attrs):        code = attrs.get("code")        mobile = attrs.get("mobile")        # 从缓存中取出        old_code = cache.get("sms_code_%s" % mobile)        if old_code and old_code == code:            user = User.objects.filter(mobile=mobile).first()            if user:                return user            else:                raise APIException("用户不存在")        else:            raise APIException("验证码验证失败")

3. 路由

点击查看代码
# 分路由from rest_framework.routers import SimpleRouterfrom . import viewsrouter = SimpleRouter()router.register("userinfo", views.UserView, "userinfo")urlpatterns = []urlpatterns += router.urls# 总路由from django.urls import path, includeurlpatterns = [    path("api/v1/user/", include("user.urls")),]# 访问http://127.0.0.1:8000/api/v1/user/userinfo/send_sms/# {"mobile":"输入手机号"}  发送POST请求 即可测试

关键词: 点击查看 把原来的 签名算法