【1】UserMobileView
from rest_framework.viewsets import ViewSet, GenericViewSet
class UserMobileView(ViewSet):
# @action(methods=['GET'], detail=False)
# def check_mobile(self, request, *args, **kwargs):
# # 手机号放在地址栏中 ?mobile=12322323232
# # 1 取出要校验的手机号
# mobile = request.query_params.get('mobile')
# # 2 数据库校验,手机号是否存在,如果不存在,返回False,如果存在,返回True
# user = User.objects.filter(mobile=mobile).first()
# assert user,'手机号不存在'
# return APIResponse(msg='手机号存在')
@action(methods=['GET'], detail=False)
def check_mobile(self, request, *args, **kwargs):
try:
mobile = request.query_params.get('mobile')
User.objects.get(mobile=mobile)
return APIResponse(msg='手机号存在')
except Exception as e:
raise Exception('手机号不存在')
【2】路由
from django.urls import path
from .views import ExceptionView, UserMobileView
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('mobile', UserMobileView, 'mobile')
urlpatterns = [
path('exception/', ExceptionView.as_view()),
]
urlpatterns += router.urls
【二】多方式登录接口
【1】安装simple-jwt模块
pip install djangorestframework-simplejwt
【2】视图类
class UserView(GenericViewSet):
serializer_class = LoginSerializer
@action(methods=['POST'], detail=False)
def mul_login(self, request, *args, **kwargs):
# 1 把校验逻辑写在序列化类中
serializer: LoginSerializer = 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)
【3】序列化类
class LoginSerializer(serializers.ModelSerializer):
username=serializers.CharField()
class Meta:
model = User
fields = ['username', 'password']
extra_kwargs = {
'password': {'write_only': True}
}
def _get_user(self, attrs):
username = attrs['username']
password = attrs['password']
if re.match(r'^1[3-9][0-9]{9}$', username):
user = User.objects.filter(mobile=username).first()
elif re.match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', 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 ValidationError('用户名或密码错误')
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.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
【4】异常处理
if isinstance(res.data, dict):
err = res.data.get('detail') or res.data.get('non_field_errors')[0] or '系统错误'
print(err)
elif isinstance(res.data, list):
err = res.data[0]
print(err)
else:
err = "服务异常请稍后再试 -drf"
response = Response({'code': 999, 'msg': err})
【三】腾讯云短信封装
# 1 发送短信,借助于第三方服务
# 2 官方都会有示例代码,发送短信
-API接口:咱们之前写的接口--》腾讯提供的:地址,请求方式,参数。。。
-使用requests模块,发送请求即可
-百分比会提供,操作麻烦
-SDK:使用不同语言写的 包
-java,php,go,python,node。。。
-pip install tencentcloud-sdk-python
# 秘钥
SecretId:AKIDrbEk9QZbR6Xq22vuo2A9wshMnBRjx8B1
SecretKey:jDZnuunfR1UtEjFslgVG16Tp8JNJ6kCV
【1】安装sdk
pip install tencentcloud-sdk-python
【2】测试
# -*- 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("AKIDrbEk9QZbR6Xq22vuo2A9wshMnBRjx8B1", "jDZnuunfR1UtEjFslgVG16Tp8JNJ6kCV")
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 = "1400635776"
# 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
# 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
req.SignName = "小猿取经公众号"
# 模板 ID: 必须填写已审核通过的模板 ID
# 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
req.TemplateId = "1049981"
# 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
req.TemplateParamSet = ["8888",'5']
# 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
# 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
req.PhoneNumberSet = ["+8618953675221"]
# 用户的 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)
【3】封装成包
# 1 包结构 libs
-tx_sms
-__init__.py #给外部使用的,在这注册
-settings.py # 配置
-sms.py # 核心
settings.py
SECRET_ID = 'AKIDrbEk9QZbR6Xq22vuo2A9wshMnBRjx8B1'
SECRET_KEY = 'jDZnuunfR1UtEjFslgVG16Tp8JNJ6kCV'
SMS_SDK_APPID = "1400635776"
SIGN_NAME = '小猿取经公众号'
TEMPLATE_ID = "1049981"
sms.py
import json
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 = json.load(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))
init
from .sms import get_code,send_sms
【四】发送短信接口
class UserMobileView(ViewSet):
@action(methods=['GET'], detail=False)
def send_sms(self, request, *args, **kwargs):
# 后续要保证发送短信接口安全
# 1 取出手机号
mobile = request.query_params.get('mobile')
# 2 生成验证码,保存到 缓存中--》后续要取出来校验
code = get_code()
print(code)
cache.set(f'cache_code_{mobile}', code) # key 要唯一,根据手机号唯一
# # 3 发送短信--》同步发送
# res=sms(mobile,code)
# # 4 返回给前端
# if res:
# return APIResponse(msg='短信发送成功')
# else:
# return APIResponse(code=101,msg='发送短信失败,请稍后再试')
# 3 异步发送短信,使用多线程,后期会用别的
t = Thread(target=sms, args=[mobile, code])
t.start()
return APIResponse(msg='短信已发送')
【五】短信登陆接口
【1】视图类
from .serializer import LoginSerializer,SMSLoginSerializer
class UserView(GenericViewSet):
serializer_class = LoginSerializer
@action(methods=['POST'], detail=False)
def mul_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)
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)
def get_serializer_class(self):
if self.action == 'sms_login':
return SMSLoginSerializer
else:
return LoginSerializer
【2】序列化类
from rest_framework import serializers
from .models import User
import re
from rest_framework.exceptions import ValidationError
from rest_framework_simplejwt.tokens import RefreshToken
from django.conf import settings
from django.core.cache import cache
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):
# 1 取出手机号,取出验证码
mobile = attrs.get('mobile')
code = attrs.get('code')
# 2 校验验证码
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
class LoginSerializer(CommonLoginSerializer, serializers.ModelSerializer):
# 这个序列化类用来: 1 校验
# 坑:必须重写username--》去除它的unique
username = serializers.CharField()
class Meta:
model = User
fields = ['username', 'password', 'icon']
extra_kwargs = {
'password': {'write_only': True} # 它不做序列化
}
def _get_user(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
# 2 去数据库校验:正则--》
if re.match(r'^1[3-9][0-9]{9}$', username):
user = User.objects.filter(mobile=username).first()
elif re.match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', 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 ValidationError('用户名或密码错误')
【六】短信注册接口
# 1 前端携带数据
-{mobile:,code:8888,password:123456}
# 3 后端
【1】视图类
# 注册接口
from .serializer import RegisterSerializer
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='注册成功')
【2】序列化类
class RegisterSerializer(serializers.ModelSerializer):
# 校验和保存(create)
code = serializers.CharField()
class Meta:
model = User
fields = ['mobile', 'password', 'code']
def validate(self, attrs):
# 1 取出code,验证code
code = attrs.pop('code')
mobile = attrs.get('mobile')
# 2 校验验证码
old_code = cache.get(f'cache_code_{mobile}')
assert old_code == code or (settings.DEBUG and code == '8888'), APIException('验证码错误')
# 2 取出手机号和密码--》创建用户-->有些字段必填
# 用户名必填
attrs['username'] = mobile
# 3 返回
return attrs
def create(self, validated_data):
# validated_data:code,mobile,password,username
user = User.objects.create_user(**validated_data)
return user
【七】多方式登陆前端
【1】模态框
LoginView
RegisterView
【2】前后端打通