• DRF03-权限与分页



    创建一个新的子应用 opt

    python manage.py startapp opt
    
    • 1

    注册子应用

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'students',
        'sers',    # 序列化器
        "school",  # 序列化器嵌套
        'req',     # 请求与响应
        'demo',    # 视图
        'opt',     # drf提供的组件使用
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    总路由,代码:

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('students/', include("students.urls")),
        path('sers/', include("sers.urls")),
        path('school/', include("school.urls")),
        path("req/", include("req.urls")),
        path("demo/", include("demo.urls")),
        path("opt/", include("opt.urls")),
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    子路由,代码:

    from django.urls import path
    from . import views
    urlpatterns = [
    
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5

    因为接下来的认证组件中需要使用到登陆功能,所以我们使用django内置admin站点并创建一个管理员.

    admin运营站点的访问地址:http://127.0.0.1:8000/admin

    python manage.py createsuperuser
    # 如果之前有账号,但是忘了,可以通过终端下的命令修改指定用户的密码,这里的密码必须8位长度以上的
    python manage.py changepassword 用户名
    
    • 1
    • 2
    • 3

    创建管理员以后,访问admin站点,先修改站点的语言配置

    settings.py

    LANGUAGE_CODE = 'zh-hans'
    
    TIME_ZONE = 'Asia/Shanghai'
    
    • 1
    • 2
    • 3

    1. 认证Authentication

    可以在配置文件中配置全局默认的认证方案

    常见的认证方式:cookie、session、token

    /home/moluo/.virtualenvs/drfdemo/lib/python3.6/site-packages/rest_framework/settings.py 默认配置文件

    REST_FRAMEWORK = {
       
        # 配置认证方式的选项
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.SessionAuthentication', # session认证
            'rest_framework.authentication.BasicAuthentication',   # 基本认证
        )
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    也可以在具体的视图类中通过设置authentication_classess类属性来设置单独的不同的认证方式

    from rest_framework.authentication import SessionAuthentication, BasicAuthentication
    from rest_framework.views import APIView
    
    class ExampleView(APIView):
        # 类属性
        authentication_classes = [SessionAuthentication, BasicAuthentication]
        def get(self,request):
            pass
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    认证失败会有两种可能的返回值,这个需要我们配合权限组件来使用:

    • 401 Unauthorized 未认证
    • 403 Permission Denied 权限被禁止

    自定义认证,drfdemo.authentication代码:

    from rest_framework.authentication import BaseAuthentication
    from django.contrib.auth import get_user_model
    
    class CustomAuthentication(BaseAuthentication):
        """
        自定义认证方式
        """
        def authenticate(self, request):
            """
            认证方法
            request: 本次客户端发送过来的http请求对象
            """
            user = request.query_params.get("user")
            pwd  = request.query_params.get("pwd")
            if user != "root" or pwd != "houmen":
                return None
            # get_user_model获取当前系统中用户表对应的用户模型类
            user = get_user_model().objects.first()
            return (user, None)  # 按照固定的返回格式填写 (用户模型对象, None)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    视图调用自定义认证,视图代码:

    from django.contrib.auth.models import AnonymousUser
    from django.shortcuts import render
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import SessionAuthentication
    from drfdemo.authentication import CustomAuthentication
    # Create your views here.
    class HomeAPIView(APIView):
        # authentication_classes = [CustomAuthentication, ]
        def get(self,request):
            """单独设置认证方式"""
            print(request.user) # 在中间件AuthenticationMiddleware中完成用户身份识别的,如果没有登录request.user值为AnonymousUser
            if request.user.id is None:
                return Response("未登录用户:游客")
            else:
                return Response(f"已登录用户:{
         request.user}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    当然,也可以注释掉上面视图中的配置,改成全局配置。settings.py,代码:

    """drf配置信息必须全部写在REST_FRAMEWORK配置项中"""
    REST_FRAMEWORK = {
       
        # 配置认证方式的选项【drf的认证是内部循环遍历每一个注册的认证类,一旦认证通过识别到用户身份,则不会继续循环】
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'drfdemo.authentication.CustomAuthentication',          # 自定义认证
            'rest_framework.authentication.SessionAuthentication',  # session认证
            'rest_framework.authentication.BasicAuthentication',    # 基本认证
        )
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2. 权限Permissions

    权限控制可以限制用户对于视图的访问和对于具有模型对象的访问。

    • 在执行视图的as_view()方法的dispatch()方法前,会先进行视图访问权限的判断
    • 在通过get_object()获取具体模型对象时,会进行模型对象访问权限的判断

    使用

    可以在配置文件中全局设置默认的权限管理类,如

    REST_FRAMEWORK = {
       
        ....
        
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        )
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    如果未指明,则采用如下默认配置

    'DEFAULT_PERMISSION_CLASSES': (
       'rest_framework.permissions.AllowAny',
    )
    
    • 1
    • 2
    • 3

    也可以在具体的视图中通过permission_classes属性来进行局部设置,如

    from django.contrib.auth.
    • 相关阅读:
      23中设计模式之访问者visitor设计模式
      【PAT甲级 - C++题解】1045 Favorite Color Stripe
      深度学习部署神器——triton inference server入门教程指北
      linux 安装配置github
      VTK--接口讲解之vtkLinearExtrusionFilter
      【Unity3D】灯光组件Light
      为什么使用RedisDesktopManager可以连上redis,微服务似乎无法访问redis
      贪吃蛇游戏代码(C语言项目)
      数据结构学习笔记——多维数组、矩阵与广义表
      如何在JavaScript中使用高阶函数
    • 原文地址:https://blog.csdn.net/weixin_42181264/article/details/132723955