zoukankan      html  css  js  c++  java
  • django 用户模块(登录 注册 搜索)接口

    django

    1. opwf_project/opwf/apps/user/model.py

      1. from django.contrib.auth.models import AbstractUser
        from django.db import models
        
        
        class User(AbstractUser):
            username = models.CharField('用户名', max_length=32,unique=True)
            password = models.CharField('密码', max_length=132)
            mobile = models.CharField('手机号', max_length=32, null=True)
            email = models.EmailField('电子邮箱', max_length=50, null=True)
        
            class Meta:
                db_table = '用户表'
                verbose_name = "用户表"
                verbose_name_plural = verbose_name
        
    2. opwf_project/opwf/apps/user/serializers.py

      1. from rest_framework import serializers
        from .models import *
        from django.contrib.auth.hashers import check_password, make_password
        
        
        class UserModelSerializer(serializers.ModelSerializer):
            class Meta:
                model = User
                fields = '__all__'
        
            # 定义创建语法:ser.save()执行,就会立刻调用create方法用来创建数据
            def create(self, validated_data):
                print(validated_data)
                # {'username': '熬了1', 'password': '123', 'mobile': '1761458369', 'email': None}
        
                validated_data["password"] = make_password(validated_data["password"])
                instance = User.objects.create(**validated_data)
        
                return instance
        
            def update(self, instance, validated_data):
                print(instance)
                print(validated_data)
                instance.username = validated_data.get("username")
                instance.mobile = validated_data.get("mobile")
                instance.email = validated_data.get("email")
                instance.save()
                return instance
        
        
    3. opwf_project/opwf/apps/user/views.py

      1. from django.db.models import Q
        from django.shortcuts import render
        # Create your views here.
        from django_filters.rest_framework import DjangoFilterBackend
        
        from rest_framework.pagination import PageNumberPagination
        from rest_framework.filters import OrderingFilter
        from rest_framework.response import Response
        from rest_framework.viewsets import ModelViewSet
        from rest_framework.views import APIView
        from rest_framework.decorators import action
        from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated, IsAuthenticatedOrReadOnly, BasePermission
        
        from .Page import PageNum
        from .Permission import MyPermission
        from .models import *
        from .serializers import *
        from rest_framework.throttling import UserRateThrottle
        
        
        # 测试与vue跨域
        class C(APIView):
            permission_classes = (AllowAny,)
        
            def get(self, request):
                return Response({"msg": "ok"})
        
        
        # 用户
        # Create your views here.
        class UserModelViewSet(ModelViewSet):
            queryset = User.objects.all()
            serializer_class = UserModelSerializer
            # 分页:自定义分页器 覆盖全局配置
            pagination_class = PageNum
        
            filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序
            # # 2.权限:自定义权限类
            permission_classes = (MyPermission,)
            # # 4.限流:自定义限流类
            # throttle_classes = [UserRateThrottle]
            # # 5.过滤:指定过滤方法类, 排序方法类, 一个或多个
            # filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序
            # # 5.1指定排序字段, 不设置, 排序功能不起效
            ordering_fields = ('date_joined', 'id')  # ?ordering=-id
            # # 5.2指定过滤字段, 不设置, 过滤功能不起效
            filter_fields = ('username', 'mobile', 'is_active')  # ?username = tom & phone = & is_active = true
        
            # 根据不同的请求, 获得不同的序列化器
        
            def get_serializer_class(self):
                if self.action == 'unactived':
                    return UserUnActiveSerializer
                else:
                    return UserSerializer
        
            @action(methods=['get'], detail=False)
            def unactived(self, request, *args, **kwargs):
                # 获取查询集, 过滤出未激活的用户
                qs = self.queryset.filter(is_active=False)
                # 使用序列化器, 序列化查询集, 并且是
                ser = self.get_serializer(qs, many=True)
                return Response(ser.data)
        
            @action(methods=['get'], detail=False)
            def actived(self, request, *args, **kwargs):
                # 获取查询集, 过滤出未激活的用户
                qs = self.queryset.filter(is_active=True)
                # 使用序列化器, 序列化查询集, 并且是
                ser = self.get_serializer(qs, many=True)
                return Response(ser.data)
        
        
        # 测试注册接口
        class RegisetrApiView(APIView):
            permission_classes = (AllowAny,)
        
            def post(self, request):
                username = request.data.get("username")
                password = request.data.get("password")
                mobile = request.data.get("mobile")
                email = request.data.get("email")
        
                ser = UserModelSerializer(data={"username": username, "password": password, "mobile": mobile, "email": email})
                # ser = UserModelSerializer(data=request.data)
                if ser.is_valid():
                    ser.save()
                    return Response({"msg": "ok"})
                else:
                    return Response({"msg": "no", "error": ser.errors})
        
        # 搜索接口
        class SearchApiView(APIView):
            def post(self, request):
                search_name = request.data.get("search_name")
        
                return Response(
                    UserModelSerializer(User.objects.filter(Q(username=search_name) | Q(mobile=search_name) | Q(email=search_name)),many=True).data)
        
        
    4. opwf_project/opwf/apps/user/urls.py

      1. from django.urls import path, include
        from rest_framework.routers import DefaultRouter
        from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
        from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
        from .views import *
        
        router = DefaultRouter()
        router.register(r'user', UserModelViewSet)
        urlpatterns = [
            path('login/', obtain_jwt_token),  # 获取token,登录视图
            path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
            path('register/', RegisetrApiView.as_view()),  # 注册视图, /user/register/
            path('search/', SearchApiView.as_view()),  # 搜索用户名  手机号  邮箱, /user/search/
        
        ]
        
        urlpatterns += router.urls
        
  • 相关阅读:
    37.使用FileWriter类向文本文件写数据
    36.使用FileReader读取文本文件
    35.使用FileOutputStream类向文本文件写数据
    34.使用FileInputStream类读取文本文件
    33.使用BufferedWriter和FileWriter类写文本文件
    32.使用BufferedReader和FileReader读取文本文件
    31.使用BufferedReader和FileReader读取文本文件
    30.解决中文乱码
    框架搭建资源 (一) V(视图)C(控制)模式
    GPS转换为百度坐标
  • 原文地址:https://www.cnblogs.com/wyx-zy/p/14032095.html
Copyright © 2011-2022 走看看