DRF(二)| 分页、权限与授权

拟墨画扇 提交于 2019-12-11 08:33:29

分页

1. PageNumberPagination

  • 局部分页
# setting.py
# drf相关配置
REST_FRAMEWORK = {
    "PAGE_SIZE": 2,
}


# views.py

from rest_framework.pagination import PageNumberPagination

class UserView(ListCreateAPIView):
    # 分页
    pagination_class = PageNumberPagination
  • 全局分页
# drf相关配置
REST_FRAMEWORK = {
    "PAGE_SIZE": 2,
    'DEFAULT_PAGINATION_CLASS': "rest_framework.pagination.PageNumberPagination",
}
  • 效果
{
    "count": 6,
    "next": "http://127.0.0.1:8000/user/?page=3",
    "previous": "http://127.0.0.1:8000/user/",
    "results": [
        {
            "url": "http://127.0.0.1:8000/user/10",
            "username": "233214",
            "password": "666888",
            "gender": "1",
            "tel": "123456789"
        },
        {
            "url": "http://127.0.0.1:8000/user/12",
            "username": "233214古典风格",
            "password": "666888",
            "gender": "1",
            "tel": "123456789"
        }
    ]
}

2. LimitOffsetPagination

  • 设置
    from rest_framework.pagination import LimitOffsetPagination
    pagination_class = LimitOffsetPagination
  • 效果
{
    "count": 6,
    "next": "http://127.0.0.1:8000/user/?limit=2&offset=4",
    "previous": "http://127.0.0.1:8000/user/?limit=2",
    "results": [
        {
            "url": "http://127.0.0.1:8000/user/10",
            "username": "233214",
            "password": "666888",
            "gender": "1",
            "tel": "123456789"
        },
        {
            "url": "http://127.0.0.1:8000/user/12",
            "username": "233214古典风格",
            "password": "666888",
            "gender": "1",
            "tel": "123456789"
        }
    ]
}

3. CursorPagination

from rest_framework.pagination import CursorPagination
pagination_class = CursorPagination
此时报错:

Cannot resolve keyword 'created' into field. Choices are: address, gender, id, password, tel, username

原因是内置分页类中默认按照‘created’字段排序,但自己写的User类中没有该字段。
解决:编写新类继承原类,重写ordeing的值

# user\paginations.py

from rest_framework.pagination import CursorPagination

# 按照tel字段排序的分页器
class TelCuroserPagination(CursorPagination):
    ordering = '-tel'
# views.py

from user.paginations import *

class UserView(ListCreateAPIView):
	pagination_class = TelCursorPagination
  • 效果
    页面显示previous/next按钮
{
    "next": "http://127.0.0.1:8000/user/?cursor=cD02Nzg5",
    "previous": "http://127.0.0.1:8000/user/?cursor=bz0xJnI9MSZwPTY3ODk%3D",
    "results": [
        {
            "url": "http://127.0.0.1:8000/user/1",
            "username": "wsm",
            "password": "666888",
            "gender": "0",
            "tel": "123456789"
        },
        {
            "url": "http://127.0.0.1:8000/user/12",
            "username": "233214古典风格",
            "password": "666888",
            "gender": "1",
            "tel": "6789"
        }
    ]
}

4. 在自定义函数中用drf分页器实现分页

# user\paginations.py

from rest_framework.pagination import CursorPagination

# 按照tel字段排序的分页器
class TelCuroserPagination(CursorPagination):
    ordering = '-tel'
# views.py

class UserView(ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    # 分页
    pagination_class = TelCursorPagination
    
    def list(self, request, *args, **kwargs):
        paginator = self.pagination_class()

        page = paginator.paginate_queryset(self.queryset, request)

        serializer = self.serializer_class(page, many=True, context={"request": request})

        return paginator.get_paginated_response(serializer.data)

权限管理

  • AllowAny
  • IsAuthenticated
  • IsAdminUser
  • IsAuthenticatedOrReadOnly
from rest_framework.permissions import IsAuthenticated

class UserView(ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    # 分页
    pagination_class = TelCursorPagination

    # 权限
    permission_classes = [IsAuthenticated]

DRF授权管理

默认采用session登录授权。
创建超级用户python manage.py createsuperuser,登录
如果报错Table 'xxx.auth_user' doesn't exist,执行迁移的两个步骤。

JWT(JSON WEB Token)授权管理

# 项目路由urls.py

from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
	
	……

    # jwt授权管理
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

]
  • 发送请求
    在这里插入图片描述
    获得两个值:
{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU3NjA1OTU5NSwianRpIjoiNmY5ZmU3ZGI1ZWNjNDkxN2E3MWRkZWFkYmM3MzkyNjAiLCJ1c2VyX2lkIjoxfQ.nRADSnDHXgQ7wf3g0cSiIF8RZZhUBDCw_omFXUek4nY",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTc1OTczNDk1LCJqdGkiOiI1Y2VhNjc4N2M3M2Y0NjIzOTA2NWY4MThlNmZjZTFmMyIsInVzZXJfaWQiOjF9.ELaRHVD9dswHNqzkPieO0v8nargj6uBORBFRjRtqCUk"
}
  1. token的使用:
    在Authorization中选择Bearer Token,填入token在这里插入图片描述
    实际上相当于在header中填入Authorization键值:在这里插入图片描述
  2. refresh的使用
    在表单中填入refresh值
    在这里插入图片描述
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!