django的rest framework框架——04

一、rest framework的分页

1、使用rest framework内置类PageNumberPagination实现分类

from django.conf.urls import url
from api import views

urlpatterns = [
    url(r‘^(?P<version>[v1|v2]+)/pager1/$‘, views.Pager1View.as_view()),
]

urls.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

from api import models
from api.utils.serializers.pager import PagerSerializer

class Pager1View(APIView):
    """分页"""
    def get(self, request, *args, **kwargs):
        roles = models.Role.objects.all()
        # 使用PageNumberPagination类进行分页
        pg = PageNumberPagination()
        # 获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 序列化分页结果
        serl = PagerSerializer(instance=pager_roles, many=True)
        return Response(serl.data)

views.py

2、继承内置类自定义分页

from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from api import models
from api.utils.serializers.pager import PagerSerializer

class MyPageNumberPagination(PageNumberPagination):
    """自定义分页类"""
    page_size = 2  # 设置一页显示2条数据
    # page_size_query_param = None  # 设置请求参数的key
    #  设置为size  可以在请求参数重置每页显示的数据条数
    page_size_query_param = "size"  # http://127.0.0.1:8082/api/v1/pager1/?size=3
    max_page_size = 5  # 设置每页最大显示的数据条数

    page_query_param = ‘page‘  # 获取页码 http://127.0.0.1:8082/api/v1/pager1/?page=2 获取第二页数据

class Pager1View(APIView):
    """分页显示"""
    def get(self, request, *args, **kwargs):

        roles = models.Role.objects.all()
        pg = MyPageNumberPagination()
        # 获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 序列化分页结果
        serl = PagerSerializer(instance=pager_roles, many=True)

        # return Response(serl.data)

        # 还可以使用内置方法返回数据
        res = pg.get_paginated_response(serl.data)
        return res

views.py

3、LimitOffsetPagination类

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
from api import models
from api.utils.serializers.pager import PagerSerializer

class Pager1View(APIView):
    """分页显示"""
    def get(self, request, *args, **kwargs):

        roles = models.Role.objects.all()
        pg = LimitOffsetPagination()  # 使用的是offset设置索引的ID
        # http://127.0.0.1:8082/api/v1/pager1/?offset=2  表示从第3条数据开始显示
        # http://127.0.0.1:8082/api/v1/pager1/?offset=2&limit=4  表示从第3条数据开始向后取4条
        # 获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 序列化分页结果
        serl = PagerSerializer(instance=pager_roles, many=True)

        return Response(serl.data)

views.py

4、CursorPagination类

from rest_framework.views import APIView
from rest_framework.pagination import CursorPagination
from api import models
from api.utils.serializers.pager import PagerSerializer

class MyCursorPagination(CursorPagination):
    """自定义分页类"""
    cursor_query_param = ‘cursor‘
    page_size = 2
    ordering = ‘id‘  # 获取数据时的排序规则
    page_size_query_param = None
    max_page_size = None

class Pager1View(APIView):
    """分页显示"""
    def get(self, request, *args, **kwargs):

        roles = models.Role.objects.all()
        pg = MyCursorPagination()
        # 获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 序列化分页结果
        serl = PagerSerializer(instance=pager_roles, many=True)

        res = pg.get_paginated_response(serl.data)
        return res

views.py

二、rest framework的视图

1、APIView

from django.conf.urls import url
from api import views

urlpatterns = [
    url(r‘^(?P<version>[v1|2]+)/viewer/$‘, views.ViewerView.as_view()),
]

urls.py

from rest_framework.views import APIView
from rest_framework.response import Response

class ViewerView(APIView):
    """继承APIView"""
    def get(self, request, *args, **kwargs):
        return Response("xxx")

views.py

2、GenericAPIView

from django.db import models

class UserGroup(models.Model):
    title = models.CharField(max_length=32)

class UserInfo(models.Model):
    user_type_choices = (
        (1, "普通用户"),
        (2, "vip"),
        (3, "svip"),
    )
    user_type = models.IntegerField(choices=user_type_choices)
    username = models.CharField(max_length=32, unique=True)
    password = models.CharField(max_length=64)
    group = models.ForeignKey(to="UserGroup", on_delete=models.CASCADE, null=True, blank=True)
    roles = models.ManyToManyField(to="Role", blank=True)

class UserToken(models.Model):
    user = models.OneToOneField(to="UserInfo")
    token = models.CharField(max_length=64)

class Role(models.Model):
    title = models.CharField(max_length=32)

class Order(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    create_time = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(to="UserInfo", on_delete=models.CASCADE, null=True, blank=True)

models.py

from django.conf.urls import url
from api import views

urlpatterns = [
    url(r‘^(?P<version>[v1|2]+)/viewer/$‘, views.ViewerView.as_view()),
]

urls.py

from rest_framework import serializers
from api import models

class ViewSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Role
        fields = "__all__"

view_serializer.py

from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

from api import models
from api.utils.serializers.view_serializer import ViewSerializer

class ViewerView(GenericAPIView):
    """继承GenericAPIView"""
    queryset = models.Role.objects.all()  # 指定要查询的数据
    serializer_class = ViewSerializer   # 序列化类
    pagination_class = PageNumberPagination  # 分页类

    def get(self, request, *args, **kwargs):
        roles = self.get_queryset()  # 获取数据
        pager = self.paginate_queryset(roles)  # 分页
        serl = self.get_serializer(instance=pager, many=True)  # 序列化
        return Response(serl.data)

views.py

3、GenericViewSet

继承了ViewSetMixin和GenericAPIView

from django.conf.urls import url
from api import views

urlpatterns = [
    url(r‘^(?P<version>[v1|2]+)/viewer/$‘, views.ViewerView.as_view({‘get‘: ‘list‘})),
]

urls.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

from api import models
from api.utils.serializers.view_serializer import ViewSerializer

class ViewerView(GenericViewSet):
    """继承GenericViewSet"""
    queryset = models.Role.objects.all()  # 指定要查询的数据
    serializer_class = ViewSerializer  # 序列化类
    pagination_class = PageNumberPagination  # 分页类

    def list(self, request, *args, **kwargs):
        roles = self.get_queryset()  # 获取数据
        pager = self.paginate_queryset(roles)  # 分页
        serl = self.get_serializer(instance=pager, many=True)  # 序列化
        return Response(serl.data)

views.py

4、ListModelMixin、CreateModelMixin、GenericViewSet

ListModelMixin内部实现了list方法:

CreateModelMixin内部实现了create方法:

from django.conf.urls import url
from api import views

urlpatterns = [
    url(r‘^(?P<version>[v1|2]+)/viewer/$‘, views.ViewerView.as_view({‘get‘: ‘list‘, ‘post‘: ‘create‘})),
]

urls.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.pagination import PageNumberPagination

from api import models
from api.utils.serializers.view_serializer import ViewSerializer

class ViewerView(ListModelMixin, CreateModelMixin, GenericViewSet):
    """继承ListModelMixin、CreateModelMixin、GenericViewSet"""
    queryset = models.Role.objects.all()  # 指定要查询的数据
    serializer_class = ViewSerializer  # 序列化类
    pagination_class = PageNumberPagination  # 分页类

views.py

5、ModelViewSet

获取单条数据、更新数据、删除数据时,URL中需要传递要操作的数据的ID

from django.conf.urls import url
from api import views

urlpatterns = [
    url(r‘^(?P<version>[v1|2]+)/viewer/(?P<pk>\d+)$‘, views.ViewerView.as_view({‘get‘: ‘retrieve‘,
                                                                                ‘post‘: ‘create‘,
                                                                                ‘delete‘: ‘destroy‘,
                                                                                ‘put‘: ‘update‘,
                                                                                ‘patch‘: ‘partial_update‘})),
]

urls.py

from rest_framework.viewsets import ModelViewSet
from rest_framework.pagination import PageNumberPagination

from api import models
from api.utils.serializers.view_serializer import ViewSerializer

class ViewerView(ModelViewSet):
    """继承ModelViewSet"""
    queryset = models.Role.objects.all()  # 指定要查询的数据
    serializer_class = ViewSerializer  # 序列化类
    pagination_class = PageNumberPagination  # 分页类

views.py

6、当使用GenericViewSet类时,会执行它父类GenericAPIView里面的get_object方法,这个方法执行了check_object_permissions方法来对对象的权限进行校验:

三、rest framework的路由

url(r‘^(?P<version>[v1|2]+)/viewer/$‘, views.ViewerView.as_view())
# http://127.0.0.1:8080/api/v2/viewer/

url(r‘^(?P<version>[v1|2]+)/viewer/$‘, views.ViewerView.as_view({‘get‘: ‘list‘, ‘post‘: ‘create‘}))
# http://127.0.0.1:8080/api/v2/viewer/
# http://127.0.0.1:8080/api/v2/viewer/?format=json  get传参的方式

url(r‘^(?P<version>[v1|2]+)/viewer\.(?P<format>\w+)$‘, views.ViewerView.as_view({‘get‘: ‘list‘, ‘post‘: ‘create‘}))
# http://127.0.0.1:8080/api/v2/viewer.json  将参数写到路径里面

自动生成路由:

from django.conf.urls import url, include
from rest_framework import routers
from api import views

router = routers.DefaultRouter()
router.register(r"role", views.ViewerView)  # url前缀,视图名称
router.register(r"group", views.ViewerView)

urlpatterns = [
    url(r‘^(?P<version>[v1|2]+)/‘, include(router.urls)),
]

urls.py

自动生成的路由:

可以通过http://127.0.0.1:8080/api/v2/role/    http://127.0.0.1:8080/api/v2/role.json等方式进行访问

四、rest framework的渲染器

1、局部配置

urlpatterns = [
    url(r‘^(?P<version>[v1|2]+)/test/$‘, views.TestView.as_view()),
]

urls.py

from rest_framework import serializers
from api import models

class ViewSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Role
        fields = "__all__"

view_serializer.py

from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer, AdminRenderer

from api import models
from api.utils.serializers.view_serializer import ViewSerializer

class TestView(APIView):
    renderer_classes = [JSONRenderer, BrowsableAPIRenderer]  # 渲染数据格式的类 http://127.0.0.1:8080/api/v2/test/?format=json
    # renderer_classes = [AdminRenderer, BrowsableAPIRenderer]  # 渲染数据格式的类 http://127.0.0.1:8080/api/v2/test/?format=admin

    def get(self, request, *args, **kwargs):
        roles = models.Role.objects.all()
        pg = PageNumberPagination()
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        serl = ViewSerializer(instance=pager_roles, many=True)
        return Response(serl.data)

views.py

2、全局配置

在项目的settings里面:

原文地址:https://www.cnblogs.com/yanlin-10/p/10257639.html

时间: 2024-10-08 02:17:45

django的rest framework框架——04的相关文章

基于Django的Rest Framework框架的认证组件

0|1一.认证组件的作用 在一个程序中有一些功能是需要登录才能使用的,原生Django中的auth组件可以用来解决这个认证问题,drf框架中也有对应的认证组件来解决这个问题. models.py from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=16) pwd = models.CharField(max_leng

基于Django的Rest Framework框架的序列化组件

本文目录 一 Django自带序列化组件 二 rest-framework序列化之Serializer 三 rest-framework序列化之ModelSerializer 四 生成hypermedialink(极少数) 五 序列化组件之请求数据校验和保存功能 序列化组件源码分析 回到目录 一 Django自带序列化组件 详见 回到目录 二 rest-framework序列化之Serializer models部分: from django.db import models # Create

基于Django的Rest Framework框架的频率组件

0|1一.频率组件的作用 在我们平常浏览网站的时候会发现,一个功能你点击很多次后,系统会让你休息会在点击,这其实就是频率控制,主要作用是限制你在一定时间内提交请求的次数,减少服务器的压力. modles.py 0|1二.自定义频率组件类 #(1)取出访问者ip # (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走 # (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内

DRF (Django REST framework) 框架介绍

Web应用模式 在开发Web应用中,有两种应用模式: 前后端不分离 前后端分离 1 前后端不分离 在前后端不分离的应用模式中,前端页面看到的效果都是由后端控制,由后端渲染页面或重定向,也就是后端需要控制前端的展示,前端与后端的耦合度很高. 这种应用模式比较适合纯网页应用,但是当后端对接App时,App可能并不需要后端返回一个HTML网页,而仅仅是数据本身,所以后端原本返回网页的接口不再适用于前端App应用,为了对接App后端还需再开发一套接口. 2 前后端分离 在前后端分离的应用模式中,后端仅返

web前端Vue+Django&#160;rest&#160;framework&#160;框架&#160;生鲜电商项目实战视频教程 学习

web前端Vue+Django rest framework 框架 生鲜电商项目实战视频教程 学习 1.drf前期准备 1.django-rest-framework官方文档 https://www.django-rest-framework.org/ #直接百度找到的djangorestframework的官网是打不开的 2.安装依赖包 如图所示,django restframework的依赖模块,除了coreapi和django-guardian,已经在前面安装过了. 打开终端,执行安装命令

Django REST framework框架详解

Django REST framework 简介 在序列化与反序列化时,虽然操作的数据不尽相同,但是执行的过程却是相似的,也就是说这部分代码是可以复用简化编写的. 在开发REST API的视图中,虽然每个视图具体操作的数据不同,但增.删.改.查的实现流程基本套路化,所以这部分代码也是可以复用简化编写的: 增:校验请求数据 -> 执行反序列化过程 -> 保存数据库 -> 将保存的对象序列化并返回 删:判断要删除的数据是否存在 -> 执行数据库删除 改:判断要修改的数据是否存在 -&g

微信开发python+django两个月的成功经历,django是个好框架!

时间:大三 上学期没有用微信内置浏览器而纯对话开发,坑了自己好一下. 下学期选错bottle框架,以为轻量好,谁知开发中什么都自己来很痛苦. 选对了框架django,终于在大三最后的个把月里写出了里程碑式的现在这个微信端,自己都感动到,作为我大三一年web开发的终结吧. 亮点1:自带后台管理 亮点2:后台权限管理 亮点3:微信回复规则设置去代码化,图形界面. 亮点4:一平台多网店 技巧:微信规则不匹配时不能回复吗?不是,规则包含空字符总能匹配任意文本,请看下面的微信规则截图. 后台 选择botl

zend framework框架学习走起——从零开始,点击记录-安装

zend framework第一步,先来安装下zend framework框架. 先介绍下,我这边的php配置环境,为图省事,我是安装wampserver来搭载php环境的,,php+Apache+mysql一下子全部搞定.所以我们的zendframwok框架安装所在文件夹就是在wampserver的www文件夹下. 我们要先去下载下来zend framework框架. 进入zend framework官网,你可以直接下载zend framework框架,也可以和我一样,选择composer方式

net.sz.framework 框架 轻松搭建数据服务中心----读写分离数据一致性,滑动缓存

前言 前文讲述了net.sz.framework 框架的基础实现功能,本文主讲 net.sz.framework.db 和 net.sz.framework.szthread; net.sz.framework.db 是 net.sz.framework 底层框架下的orm框架,仿照翻译了hibernate实现功能,虽然不足hibernate强大:但在于其功能实现单一高效和高可控性: net.sz.framework.szthread 是 net.sz.framework 底层框架下的线程控制中