前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >实战:用户模块,登录注册接口

实战:用户模块,登录注册接口

作者头像
HammerZe
发布2022-05-09 18:46:54
9610
发布2022-05-09 18:46:54
举报
文章被收录于专栏:Hammer随笔

实战:用户模块,登录注册接口

视图

代码语言:javascript
复制
from django.shortcuts import render
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from django.contrib.auth.hashers import make_password, check_password
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings

from .models import *
from .serializer import UserSerializer




# 注册视图
class UserRegisterView(ViewSet):
    @action(methods=["POST"], detail=False)
    def register(self, request):
        usernmae = request.data.get('username')
        password = request.data.get('password')
        re_password = request.data.get('re_password')
        is_superuser = request.data.get('is_superuser')
        if User.objects.filter(username=usernmae):
            return Response({'msg': f'用户{usernmae}已注册!', 'code': 400})
        else:
            if password == re_password:
                user_date = {'username': usernmae, 'password': make_password(password), 'is_superuser': is_superuser}
                user_serializer = UserSerializer(data=user_date)
                if user_serializer.is_valid():
                    user_serializer.save()
                    return Response({'code': 201, 'msg': f'用户{usernmae}注册成功'})
                else:
                    print(user_serializer.errors)
                    return Response({'code': 401, 'msg': '注册失败', 'errors': user_serializer.errors})
            else:
                return Response({'msg': '两次密码不一致', 'code': 402})


class UserLoginView(ViewSet):
    @action(methods=["POST"], detail=False)
    def login(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        # 载荷
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        response_dict = {'code': 100, 'msg': None}
        if user and check_password(password, user.password):
            # 登录成功签发token

            # 载荷
            payload = jwt_payload_handler(user)
            # token
            token = jwt_encode_handler(payload)
            response_dict['token'] = token
            response_dict['msg'] = f'{user.username} Login successfuly!'

        else: # 登录失败
            response_dict['code'] = 101
            response_dict['msg'] = 'Login Failed, The user name or password is incorrect! '
        return Response(response_dict)

序列化

代码语言:javascript
复制
from rest_framework import serializers

from .models import *

# 逻辑写视图
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

模型

代码语言:javascript
复制
from django.contrib.auth.models import AbstractUser
from django.db import models

# 用户表
class User(AbstractUser):
    telephone = models.CharField(max_length=11, null=True, unique=True)

    class Meta:
        verbose_name_plural = '用户表'

    def __str__(self):
        return self.username

路由

代码语言:javascript
复制
from django.contrib import admin
from django.urls import path,include
from app01 import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()

router.register('user',views.UserLoginView,'user')
router.register('user',views.UserRegisterView,'user')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(router.urls)),
]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实战:用户模块,登录注册接口
    • 视图
      • 序列化
        • 模型
          • 路由
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档