DRF-Django rest framework
1. 基于jwt的多方式登陆
1. 需求分析
1. 登录方式
1. 手机号+密码
2. 用户名+密码
3. 邮箱+密码
2. 流程分析(post请求)
路由: 自动生成
视图类: ViewSet(ViewSetMixin, views.APIView)
序列化类:重写validate方法,在这里面对用户名和密码进行校验
3. 代码实现
如下.....
2. 代码实现
1. 路由
path('login/', views.LoginViewSet.as_view({
'post':'create'})),
2. 视图
class LoginViewSet(ViewSet):
def create(self, request, *args, **kwargs):
ser = LoginSerializer(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)
3. 序列化类
from rest_framework import serializers
from app01.models import UserInfo
import re
from rest_framework.exceptions import ValidationError
from rest_framework_jwt.utils import jwt_encode_handler, jwt_payload_handler
from rest_framework_jwt.views import obtain_jwt_token
class LoginSerializer(serializers.ModelSerializer):
username = serializers.CharField()
class Meta:
model = UserInfo
fields = ['username', 'password']
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
if re.match('^1[3-9]\d{9}$', username):
user = UserInfo.objects.filter(phone=username).first()
elif re.match('^.+@.+$', username):
user = UserInfo.objects.filter(email=username).first()
else:
user = UserInfo.objects.filter(username=username).first()
if user and user.check_password(password):
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
self.cont