zoukankan      html  css  js  c++  java
  • DRF之权限认证,过滤分页,异常处理

    1. 认证Authentication

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

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.BasicAuthentication',   # 基本认证
            'rest_framework.authentication.SessionAuthentication',  # session认证
        )
    }
    View Code

    也可以在每个视图中通过设置authentication_classess属性来设置

    from rest_framework.authentication import SessionAuthentication, BasicAuthentication
    from rest_framework.views import APIView
    
    class ExampleView(APIView):
        authentication_classes = (SessionAuthentication, BasicAuthentication)
        ...
    View Code

    认证失败会有两种可能的返回值:

    • 401 Unauthorized 未认证

    • 403 Permission Denied 权限被禁止

    2. 权限Permissions

    权限控制可以限制用户对于视图的访问和对于具体数据对象的访问。

    • 在执行视图的dispatch()方法前,会先进行视图访问权限的判断

    • 在通过get_object()获取具体对象时,会进行模型对象访问权限的判断

    使用

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

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        )
    }
    View Code

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

    'DEFAULT_PERMISSION_CLASSES': (
       'rest_framework.permissions.AllowAny',
    )
    View Code

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

    demo:

    from rest_framework.permissions import IsAuthenticated
    from rest_framework.views import APIView
    
    class ExampleView(APIView):
        permission_classes = (IsAuthenticated,)
        ...
    View Code

    提供的权限

    • AllowAny 允许所有用户

    • IsAuthenticated 仅通过认证的用户

    • IsAdminUser 仅管理员用户

    • IsAuthenticatedOrReadOnly 已经登陆认证的用户可以对数据进行增删改操作,没有登陆认证的只能查看数据。

    自定义权限

    如需自定义权限,需继承rest_framework.permissions.BasePermission父类,并实现以下两个任何一个方法或全部

    • .has_permission(self, request, view)

      是否可以访问视图, view表示当前视图对象

    • .has_object_permission(self, request, view, obj)

      是否可以访问数据对象, view表示当前视图, obj为数据对象

    demo:

    View Code

    实例:

    from django.shortcuts import render
    from rest_framework.authentication import SessionAuthentication, BasicAuthentication
    
    from auth.serializers import BookInfoSerializer
    from demo1.models import BookInfo
    # Create your views here.
    from rest_framework.viewsets import ModelViewSet
    
    
    # 自定义权限认证
    from rest_framework.permissions import BasePermission, IsAuthenticatedOrReadOnly
    
    
    class CustomPermission(BasePermission):
        def has_permission(self, request, view):
            # 当前权限方法用于判断访问者是否权限访问对应视图
            # 获取当前已经登录的用户可以通过 request.user
                return request.user.username =='mixtea'
    
    class CompoentModelViewSet(ModelViewSet):
        queryset = BookInfo.objects.all()
        serializer_class = BookInfoSerializer
        # 设置认证方式
        authentication_classes = (SessionAuthentication, BasicAuthentication)
        # 设置自定义权限
        permission_classes = [CustomPermission]
    View Code

    3. 限流Throttling

    可以对接口访问的频次进行限制,以减轻服务器压力。

    一般用于付费购买次数,投票等场景使用.

    使用

    可以在配置文件中,使用DEFAULT_THROTTLE_CLASSESDEFAULT_THROTTLE_RATES进行全局配置,

    REST_FRAMEWORK = {
        'DEFAULT_THROTTLE_CLASSES': (
            'rest_framework.throttling.AnonRateThrottle',
            'rest_framework.throttling.UserRateThrottle'
        ),
        'DEFAULT_THROTTLE_RATES': {
            'anon': '100/day',
            'user': '1000/day'
        }
    }
    View Code

    DEFAULT_THROTTLE_RATES 可以使用 second, minute, hourday来指明周期。

     

    也可以在具体视图中通过throttle_classess属性来配置,如

    from rest_framework.throttling import UserRateThrottle
    from rest_framework.views import APIView
    
    class ExampleView(APIView):
        throttle_classes = (UserRateThrottle,)
        ...
    View Code

    可选限流类

    1) AnonRateThrottle

    限制所有匿名未认证用户,使用IP区分用户。  使用 DEFAULT_THROTTLE_RATES['anon']  来设置频次

    2)UserRateThrottle

    限制认证用户,使用User id 来区分。  使用 DEFAULT_THROTTLE_RATES['user']  来设置频次

    3)ScopedRateThrottle.  

    限制用户对于每个视图的访问频次,使用ip或user id。

    例如:

    from rest_framework.authentication import SessionAuthentication
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.generics import RetrieveAPIView
    from rest_framework.throttling import UserRateThrottle
    
    class BookDetailView(RetrieveAPIView):
        queryset = BookInfo.objects.all()
        serializer_class = BookInfoSerializer
        authentication_classes = [SessionAuthentication]
        permission_classes = [IsAuthenticated]
        throttle_classes = (UserRateThrottle,)
    View Code

    4. 过滤Filtering

    对于列表数据可能需要根据字段进行过滤,我们可以通过添加django-fitlter扩展来增强支持。

    pip install django-filter

     在安装完 django-fitlter 之后,若想要使用, 必须在settings 中 注册   'django_filters',   应用,

    在配置文件中增加过滤后端的设置:

    INSTALLED_APPS = [
        ...
        'django_filters',  # 需要注册应用,
    ]
    
    REST_FRAMEWORK = {
        ...
        'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
    }
    View Code

    在视图中添加filter_fields属性,指定可以过滤的字段

    class BookListView(ListAPIView):
        queryset = BookInfo.objects.all()
        serializer_class = BookInfoSerializer
        filter_fields = ('btitle', 'bread')
    
    # 127.0.0.1:8000/books/?btitle=西游记
    View Code

    5. 排序

    对于列表数据,REST framework提供了OrderingFilter过滤器来帮助我们快速指明数据按照指定字段进行排序。

    使用方法:

    在类视图中设置filter_backends,使用rest_framework.filters.OrderingFilter过滤器,REST framework会在请求的查询字符串参数中检查是否包含了ordering参数,如果包含了ordering参数,则按照ordering参数指明的排序字段对数据集进行排序。

    前端可以传递的ordering参数的可选字段值需要在ordering_fields中指明。

    示例:

    class BookListView(ListAPIView):
        queryset = BookInfo.objects.all()
        serializer_class = BookInfoSerializer
        filter_backends = [OrderingFilter]
        ordering_fields = ('id', 'bread', 'bpub_date')
    
    # 127.0.0.1:8000/books/?ordering=-bread
    View Code

    6. 分页Pagination

    REST framework提供了分页的支持。

    我们可以在配置文件中设置全局的分页方式,如:

    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS':  'rest_framework.pagination.PageNumberPagination',
        'PAGE_SIZE': 100  # 每页数目
    }
    View Code

    也可通过自定义Pagination类,来为视图添加不同分页行为。在视图中通过pagination_clas属性来指明。

    #声明分页器
    class LargeResultsSetPagination(PageNumberPagination):
        page_size = 1000
        page_size_query_param = 'page_size'
        max_page_size = 10000
    class BookDetailView(RetrieveAPIView):
        queryset = BookInfo.objects.all()
        serializer_class = BookInfoSerializer
        pagination_class = LargeResultsSetPagination
    View Code

    **注意:如果在视图内关闭分页功能,只需在视图内设置**

    pagination_class = None

    可选分页器

    1) PageNumberPagination

    前端访问网址形式:

    GET  http://api.example.org/books/?page=4

    可以在子类中定义的属性:

    • page_size 每页数目

    • page_query_param 前端发送的页数关键字名,默认为"page"

    • page_size_query_param 前端发送的每页数目关键字名,默认为None

    • max_page_size 前端最多能设置的每页数量

    demo:

    from rest_framework.pagination import PageNumberPagination
    
    class StandardPageNumberPagination(PageNumberPagination):
        page_size_query_param = 'page_size'
        max_page_size = 10
    
    class BookListView(ListAPIView):
        queryset = BookInfo.objects.all().order_by('id')
        serializer_class = BookInfoSerializer
        pagination_class = StandardPageNumberPagination
    
    # 127.0.0.1/books/?page=1&page_size=2
    View Code

    2)LimitOffsetPagination

    前端访问网址形式:

    GET http://api.example.org/books/?limit=100&offset=400

    可以在子类中定义的属性:

    • default_limit 默认限制,默认值与PAGE_SIZE设置一直

    • limit_query_param limit参数名,默认'limit'

    • offset_query_param offset参数名,默认'offset'

    • max_limit 最大limit限制,默认None

    from rest_framework.pagination import LimitOffsetPagination
    
    class BookListView(ListAPIView):
        queryset = BookInfo.objects.all().order_by('id')
        serializer_class = BookInfoSerializer
        pagination_class = LimitOffsetPagination
    
    # 127.0.0.1:8000/books/?offset=3&limit=2
    View Code

    7. 异常处理 Exceptions

    REST framework提供了异常处理,我们可以自定义异常处理函数。

    from rest_framework.views import exception_handler # drf默认提供的异常处理函数
    
    def custom_exception_handler(exc,context):
        """自定义的异常处理
        exc就是异常类,可以通过使用isinstance来判断异常发生时,属于哪一种异常类型
    
        context 就是异常发生时的上下文信息
        """
    
        # 先调用REST framework默认的异常处理方法获得标准错误响应对象
        response = exception_handler(exc,context)
    
        # print(isinstance(exc,ZeroDivisionError))
        # print(context)
    
        # 在此处补充自定义的异常处理
        if response is not None:
            response.data['status_code'] = response.status_code
    
        return response
    View Code

    在配置文件中声明自定义的异常处理:

       # 设置自定义异常处理函数
        'EXCEPTION_HANDLER': 'DRF.exceptions.custom_exception_handler'
    View Code

    如果未声明,会采用默认的方式,如下

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
    }
    View Code

    例如:

    补充上处理关于数据库的异常demo:

    from rest_framework.views import exception_handler as drf_exception_handler
    from rest_framework import status
    from django.db import DatabaseError
    
    def exception_handler(exc, context):
        response = drf_exception_handler(exc, context)
    
        if response is None:
            view = context['view']
            if isinstance(exc, DatabaseError):
                print('[%s]: %s' % (view, exc))
                response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    
        return response
    View Code

    以下是REST framework定义的异常

    • APIException 所有异常的父类

    • ParseError 解析错误

    • AuthenticationFailed 认证失败

    • NotAuthenticated 尚未认证

    • PermissionDenied 权限决绝

    • NotFound 未找到

    • MethodNotAllowed 请求方式不支持

    • NotAcceptable 要获取的数据格式不支持

    • Throttled 超过限流次数

    • ValidationError 校验失败

  • 相关阅读:
    实验四 Linux系统搭建C语言编程环境
    实验三 Linux系统用户管理及VIM配置
    实验二 Linux系统简单文件操作命令
    《Linux命令行与shell脚本编程大全》勘错
    考研英语每天一段阅读理解
    仓储管理系统500bug记录一下mysql 8小时超时解决办法
    win7 64位4GB内存下 tomcat7扩大内存
    解决远程连接mysql错误1130代码的方法
    win7 64 位 tomcat 定时重启脚本
    通过Navicat for MySQL远程连接的时候报错mysql 1130
  • 原文地址:https://www.cnblogs.com/Mixtea/p/10567389.html
Copyright © 2011-2022 走看看