zoukankan      html  css  js  c++  java
  • (5)DRF框架——其他

    认证和权限

    全局配置

    在settings文件里面添加(只针对继承rest_framework的视图有用)

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.BasicAuthentication',   # 基本认证
            'rest_framework.authentication.SessionAuthentication',  # session认证
        ),
        'DEFAULT_PERMISSION_CLASSES': (
                'rest_framework.permissions.IsAuthenticated',#权限
                    # AllowAny允许所有用户
                    # IsAuthenticated仅通过认证的用户
                    # IsAdminUser仅管理员用户
                    # IsAuthenticatedOrReadOnly认证的用户可以完全操作,否则只能获取读取
            )
    }

    局部配置

    from rest_framework.authentication import BasicAuthentication, SessionAuthentication
    from rest_framework.permissions import IsAuthenticated
    
    from .models import BookInfo
    from .serializer import BookModelSerislzier
    from rest_framework.viewsets import ModelViewSet
    
    class BooksView(ModelViewSet):
        #查询多个 和新增数据
        queryset = BookInfo.objects.all()#指定当前类视图使用的查询集数据
        serializer_class = BookModelSerislzier #指定类视图使用的序列化器类 注意后面没有括号 只是类名
        #认证
        authentication_classes = (BasicAuthentication,SessionAuthentication)
        #权限
        permission_classes = (IsAuthenticated,)#注意这里是元组 最后要加逗号

    限流

    全局配置 用户限流

    REST_FRAMEWORK = {
        #开启用户限流
        'DEFAULT_THROTTLE_CLASSES': (
            'rest_framework.throttling.AnonRateThrottle',#匿名用户
            'rest_framework.throttling.UserRateThrottle'#注册用户
        ),
        #指定限流次数
        'DEFAULT_THROTTLE_RATES': {
            'anon': '100/day',#匿名用户
            'user': '1000/day'#注册用户
        }
    }

    局部配置 用户限流

    class BooksView(ModelViewSet):
        #查询多个 和新增数据
        queryset = BookInfo.objects.all()#指定当前类视图使用的查询集数据
        serializer_class = BookModelSerislzier #指定类视图使用的序列化器类 注意后面没有括号 只是类名
    
        throttle_classes = [UserRateThrottle]#开启注册用户限流

    视图限流

    class ContactDetailView(APIView):
        throttle_scope = 'contacts'
        ...
    
    class UploadView(APIView):
        throttle_scope = 'uploads'
        ...
    REST_FRAMEWORK = {
        #开启视图限流
        'DEFAULT_THROTTLE_CLASSES': (
            'rest_framework.throttling.ScopedRateThrottle',
        ),
        #指定不同视图的次数
        'DEFAULT_THROTTLE_RATES': {
            'contacts': '1000/day',
            'uploads': '20/day'
        }
    }

    过滤

    添加拓展

    pip insall django-filter

    注册应用

    INSTALLED_APPS = [
        ...
        'django_filters',  # 需要注册应用,
    ]

    配置

    REST_FRAMEWORK = {
        'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
    }

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

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

    排序

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

    前端可以传递的ordering参数的可选附加值需要在ordering_fields中指定。

    from .models import BookInfo
    from .serializer import BookModelSerislzier
    from rest_framework.viewsets import ModelViewSet
    from rest_framework.filters import OrderingFilter#导入排序方法类
    
    class BooksView(ModelViewSet):
        #查询多个 和新增数据
        queryset = BookInfo.objects.all()#指定当前类视图使用的查询集数据
        serializer_class = BookModelSerislzier #指定类视图使用的序列化器类 注意后面没有括号 只是类名
    
        #指定排序的方法类
        filter_backends = [OrderingFilter]
        #指定排序字段
        ordering_fields=('id',)
    
    # 127.0.0.1:8000/books/?ordering=-id

    分页

    全局指定

    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS':  'rest_framework.pagination.PageNumberPagination',#指定使用的分页器类
        'PAGE_SIZE': 100  # 每页数目
    }

    然后只要指定页数就行了 视图中不操作

    http://127.0.0.1:8000/books/?page=2

    局部自定义分页器类

    from rest_framework.pagination import PageNumberPagination#导入分页器类
    
    class PageNum(PageNumberPagination):
    
        page_size_query_param = 'page_size'#指定控制每页数量 的 参数
        max_page_size = 6 #指定每页最大返回数量

    在视图下应用

    class BooksView(ModelViewSet):
        #查询多个 和新增数据
        queryset = BookInfo.objects.all()#指定当前类视图使用的查询集数据
        serializer_class = BookModelSerislzier #指定类视图使用的序列化器类 注意后面没有括号 只是类名
        #指定使用的分页器类
        pagination_class = PageNum

    使用

    http://127.0.0.1:8000/books/?page_size=2&page=1
    #page第几页 
    #page_size 之前指定的参数 指定每页几个数据

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

    pagination_class = None

    还有一种 LimitOffsetPagination 分页器类 区别是参数不一样

    异常处理

    REST框架定义的异常

    • APIException所有异常的父类
    • ParseError解析错误
    • 认证失败认证失败
    • 未认证未认证
    • PermissionDenied权限决绝
    • 未找到
    • MethodNotAllowed请求方式不支持
    • 要接受的数据格式不支持
    • 超过限制流次数
    • ValidationError校验失败

    定义一个数据库异常处理类

    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

    在配置中指定一下

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
    }

    自动生成接口文档

    REST framework可以自动帮助我们生成接口文档。

    接口文档以网页的方式呈现。

    自动接口文档能生成的是继承自APIView及其子类的视图。

    pip install coreapi

    在总路由中添加

    from rest_framework.documentation import include_docs_urls
    
    urlpatterns = [
      ... url(r
    '^docs/', include_docs_urls(title='My API title'))   ...
    ]

    访问 127.0.0.1:8000/docs/

    如果报错 'AutoSchema' object has no attribute 'get_link'

    则在配置中添加

    REST_FRAMEWORK = {
        'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'
    }
  • 相关阅读:
    洛谷P3886 [JLOI2009]神秘的生物(插头dp)
    Leetcode 842 将数组拆分成斐波那契序列
    Leetcode 08.07 无重复字符串的排列组合
    Leetcode131 分割回文串
    Leetcode 516 最长回文子序列
    Leetcode08.12 N皇后
    Leetcode 813 最大平均值和分组
    Leetcode 79 单词搜索 二维平面上的回溯
    题解 洛谷 P4694 【[PA2013]Raper】
    跳表的基本认识
  • 原文地址:https://www.cnblogs.com/xujin247/p/11728701.html
Copyright © 2011-2022 走看看