目录
腾讯云短信开发
使用第三方 腾讯云短信平拍
API和SDK 尽量选择SDK
SDK 版本:3.0版本 不仅仅有发短信的功能,还有其他的云功能
2.0版本 比较简单 只有发送短信的功能
如何安装SDK:
方式一: pip install tencentcloud-sdk-python
方式二:源码安装
1.下载好sdk源码包
2.在pycharm中用终端切换到sdk源码的路径中
3.然后使用 python setup.py install
4.这样就会把你下载好的源码 安装到你当前的解释器环境下
封装发送短信接口
libs文件夹下 创建 send_sms_v3 文件夹
send_sms_v3
__init__.py
settings.py
sms.py
__init__.py代码
from .sms import get_code,send_sms
# 在init中导入功能,这样就可以通过导入文件包 直接导入该功能
----------------------------------------------------------------
settings.py代码
SECRET_ID = 'AKIDfCa3eHnoriOyObXXXahdOucGk1DPY'
SECRET_KEY = 'zjQ0UmriQyLZXXAOct6X3d2Of'
APP_ID = '14005XX4913'
SING_NAME = "小XXX公众号"
TEMPLATE_ID = "17XX61"
# 需要填写的信息设置为配置
----------------------------------------------------------------
sms.py代码 中放置真正的发送短信示例代码
import random
# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
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 . import settings
import json
# 生成N为数字验证码的函数
def get_code(number=4):
code = ''
for i in range(number):
i = random.randint(0, 9)
code += str(i)
return code
# 编写发送短信的函数
def send_sms(code, phone):
try:
cred = credential.Credential(settings.SECRET_ID, settings.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
client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
req = models.SendSmsRequest()
req.SmsSdkAppId = settings.APP_ID
req.SignName = settings.SING_NAME
req.TemplateId = settings.TEMPLATE_ID
req.TemplateParamSet = [code, '1']
req.PhoneNumberSet = ["+86" + phone]
# 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
req.SessionContext = ""
# 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手]
req.ExtendCode = ""
# 国际/港澳台短信 senderid(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手]
req.SenderId = ""
resp = client.SendSms(req)
# 输出json格式的字符串回包
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
发送短信验证码接口
from LufeiApi.libs.send_sms_v3 import get_code,send_sms
@action(methods=['POST'],detail=False)
def send_msg(self,request):
try:
phone = request.data['phone']
code = get_code()
res = send_sms(code,phone)
if res:
# 通过send_sms的返回值来判断是否发送成功
return MyResponse(msg='发送成功')
else:
return MyResponse(msg='发送失败')
except Exception as e:
raise APIException(str(e))
多线程编写短信验证码接口
from LufeiApi.libs.send_sms_v3 import get_code,send_sms
from threading import Thread
@action(methods=['POST'],detail=False)
def send_msg(self,request):
try:
phone = request.data['phone']
code = get_code()
t=Thread(target=send_sms,args=[code,phone])
# 使用异步 创建多线程 来执行 send_sms方法
t.start()
return MyResponse(msg='短信已发送')
# 由于使用了多线程 那只能都算发送成功了
except Exception :
raise APIException(str('手机号码错误'))
短信验证码登录view
1.取出前端传来的 手机号和验证码 并校验是否正确
2.在发送验证码接口 缓存 存储验证码
3.根据手机号查询用户,有则签发token
4.将token返回给前端
def get_serializer_class(self):
if self.action == 'login_sms':
return UserPhoneLoginSerializer
else:
return UserLoginSerializer
# 通过重写get_serializer_class方法 来分别对不同功能执行不同序列化类
@action(methods=['POST'], detail=False)
def login_mul(self, request, *args, **kwargs):
return self._login(request, *args, **kwargs)
@action(methods=['POST'], detail=False)
def login_sms(self, request, *args, **kwargs):
return self._login(request, *args, **kwargs)
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 MyResponse(token=token, username=username)
# 由于短信验证码登录和账号密码登录区别只有 使用的序列化类不同,
# 所以我们把相同代码抽离 写一个方法 解决代码繁多问题
# 在序列化类中 进行逻辑处理 判断传入的手机号和验证码是否正确
短信验证码登录序列化类
# 由于我们数据库没有code字段 需要定义这个字段
# 由于数据库中phone字段自带唯一值校验 所以也需要重写
class UserPhoneLoginSerializer(serializers.ModelSerializer):
code = serializers.CharField()
phone = serializers.CharField()
class Meta:
model = User
fields = ['phone', 'code']
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):
phone = attrs.get('phone')
code = attrs.get('code')
# 拿到请求发送验证码接口时 存入缓存的code (当时以KV键值对存储的)
odl_code = cache.get('sms_phone_%s' % phone)
# 判断验证码是否正确
if code == odl_code:
user = User.objects.filter(phone=phone).first()
# 判断手机号是否正确
if user:
return user
else:
raise APIException('手机号不存在')
else:
raise APIException('验证码错误')
return user
def _get_token(self, user):
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
短信注册接口
前端传来数据 {'username':'22929102','password':'22222','phone':'1883882888'}
class RegisterView(GenericViewSet,CreateModelMixin):
queryset = User.objects.all()
serializer_class = RegisterSerializer
def create(self, request, *args, **kwargs):
super().create(request, *args, **kwargs)
return MyResponse(msg='注册成功')
# 重写这个方法 只是为了 成功时返回我们的逻辑 注册成功 逻辑都在序列化中
注册序列化类
class RegisterSerializer(serializers.ModelSerializer):
username = serializers.CharField()
# 重写字段 规避自带的唯一值校验
phone = serializers.CharField()
# 重写字段 规避自带的唯一值校验
class Meta:
model = User
fields = ['username', 'password', 'phone']
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
phone = attrs.get('phone')
if username and phone and password:
# 判断是否都有传值
user = User.objects.filter(username=username).first()
if user:
raise APIException('用户名已存在')
user = User.objects.filter(phone=phone).first()
if user:
raise APIException('手机号不能重复注册')
else:
raise APIException('请填写正确的账户和手机号')
return attrs
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
# 用通过校验的数据 创建用户
return user
标签:code,短信,登录,get,self,sms,phone,腾讯
From: https://www.cnblogs.com/moongodnnn/p/17189765.html