Loading

短信接口封装

腾讯云短信封装

发送短信

# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
    # SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi
    cred = credential.Credential("123123", "123123")
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30    # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
 
    # 非必要步骤:
    # 实例化一个客户端配置对象,可以指定超时时间等配置
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
    clientProfile.language = "en-US"
    clientProfile.httpProfile = httpProfile
 
    # 实例化要请求产品(以sms为例)的client对象
    # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
    client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
    req = models.SendSmsRequest()
    # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
    req.SmsSdkAppId = "123123"
    # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
    # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
    req.SignName = "123123"
    # 模板 ID: 必须填写已审核通过的模板 ID
    # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
    req.TemplateId = "123123"
    # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
    req.TemplateParamSet = ["8888",'5']
    # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
    # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
    req.PhoneNumberSet = ["+8615666777888"]
    # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
    req.SessionContext = ""
    # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手]
    req.ExtendCode = ""
    # 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId,无需填写该字段。注:月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。
    req.SenderId = ""
 
    resp = client.SendSms(req)
    # 输出json格式的字符串回包
    print(resp.to_json_string(indent=2))
 
except TencentCloudSDKException as err:
    print(err)

封装成包

# 1 包结构 libs
	-tx_sms
    	-__init__.py #给外部使用的,在这注册
        -settings.py # 配置
        -sms.py      # 核心

settings

SECRET_ID = ''
SECRET_KEY = ''
SMS_SDK_APPID = ""
SIGN_NAME = ''
TEMPLATE_ID = ""

sms

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from .settings import *
import random
 
 
# 生成n位数字的随机验证码
def get_code(num=4):
    code = ''
    for i in range(num):
        r = random.randint(0, 9)
        code += str(r)
 
    return code
 
 
# 发送短信函数
def send_sms(mobile, code):
    try:
        cred = credential.Credential(SECRET_ID, SECRET_KEY)
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
 
        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
 
        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
        req = models.SendSmsRequest()
        # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
        req.SmsSdkAppId = SMS_SDK_APPID
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
        # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
        req.SignName = SIGN_NAME
        # 模板 ID: 必须填写已审核通过的模板 ID
        # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
        req.TemplateId = TEMPLATE_ID
        # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
        req.TemplateParamSet = [code, '1']
        # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
        req.PhoneNumberSet = [f"+86{mobile}"]
        # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = ""
        # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手]
        req.ExtendCode = ""
        # 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId,无需填写该字段。注:月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。
        req.SenderId = ""
        resp = client.SendSms(req)
        # 输出json格式的字符串回包
        res = 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
 
 
if __name__ == '__main__':
    print(get_code(3))

发送短信接口

GET - http://127.0.0.1:8000/api/v1/user/mobile/send_sms/?mobile=

views

class UserMobileView(GenericViewSet):
    @action(methods=['GET'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        mobile = request.query_params.get('mobile')
        code = get_code()
        print(code)
        cache.set(f'cache_code_{mobile}', code)
        # 发送短信 - 同步发送
        # res=sms(mobile,code)
        # 返回给前端
        # if res:
        #     return APIResponse(msg='短信发送成功')
        # else:
        #     return APIResponse(code=101,msg='发送短信失败,请稍后再试')
        t = Thread(target=sms, args=[mobile, code])
        t.start()
        return APIResponse(msg='短信已发送')

短信登陆接口

POST - http://127.0.0.1:8000/api/v1/user/mul_login/sms_login/

之前写过多方式登录,代码一样,可以抽出来做成公用的

views

class UserLoginView(GenericViewSet):
    serializer_class = LoginSerializer
 
    def get_serializer_class(self):
        if self.action == 'sms_login':
            return SMSLoginSerializer
        else:
            return LoginSerializer
 
    def _login(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = serializer.context.get('token')
        username = serializer.context.get('username')
        icon = serializer.context.get('icon')
        return APIResponse(token=token, username=username, icon=icon)
 
    @action(methods=['POST'], detail=False)
    def multiple_login(self, request, *args, **kwargs):
        return self._login(request, *args, **kwargs)
 
    @action(methods=['POST'], detail=False)
    def sms_login(self, request, *args, **kwargs):
        return self._login(request, *args, **kwargs)

SMSLoginSerializer

这个地方一样,序列化类也可以抽出来

class CommonLoginSerializer():
    def _get_user(self, attrs):
        raise Exception('这个方法必须被重写')
 
    def _get_token(self, user):
        refresh = RefreshToken.for_user(user)
        return str(refresh.access_token)
 
    def _pre_data(self, token, user):
        self.context['token'] = token
        self.context['username'] = user.username
        # self.instance=user # 当前用户,放到instance中了
        self.context['icon'] = settings.BACKEND_URL + "media/" + str(user.icon)  # 不带 域名前缀的
 
    def validate(self, attrs):
        # 1 取出用户名(手机号,邮箱)和密码
        user = self._get_user(attrs)
        # 2 如果存在:签发token,返回
        token = self._get_token(user)
        # 3 把token,用户名和icon放入context
        self._pre_data(token, user)
        return attrs
 
 
class SMSLoginSerializer(CommonLoginSerializer, serializers.Serializer):
    code = serializers.CharField()
    mobile = serializers.CharField()
 
    def _get_user(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get(f'cache_code_{mobile}')
        assert old_code == code or (settings.DEBUG and code == '8888'), ValidationError('验证码错误')
        user = User.objects.filter(mobile=mobile).first()
        assert user, ValidationError('该手机号未注册!')
        return user

短信注册接口

POST - http://127.0.0.1:8000/api/v1/user/register/

views

class UserRegisterView(GenericViewSet):
    serializer_class = RegisterSerializer
 
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return APIResponse(msg='注册成功')

RegisterSerializer

class RegisterSerializer(serializers.ModelSerializer):
    code = serializers.CharField()
 
    class Meta:
        model = User
        fields = ['mobile', 'password', 'code']
 
    def validate(self, attrs):
        code = attrs.pop("code")
        mobile = attrs.get('mobile')
        old_code = cache.get(f'cache_code_{mobile}')
        assert old_code == code or (settings.DEBUG and code == '8888'), ValidationError('验证码错误')
        attrs['username'] = mobile
        return attrs
 
 
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

课程(分类、列表、详情)接口

posted @ 2024-06-10 15:00  HuangQiaoqi  阅读(20)  评论(0编辑  收藏  举报