1、rest framework的分頁git
一、使用rest framework內置類PageNumberPagination實現分類django
from django.conf.urls import url from api import views urlpatterns = [ url(r'^(?P<version>[v1|v2]+)/pager1/$', views.Pager1View.as_view()), ]
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)
二、繼承內置類自定義分頁json
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
三、LimitOffsetPagination類api
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)
四、CursorPagination類ide
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
2、rest framework的視圖post
一、APIViewurl
from django.conf.urls import url from api import views urlpatterns = [ url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view()), ]
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")
二、GenericAPIViewspa
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)
from django.conf.urls import url from api import views urlpatterns = [ url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view()), ]
from rest_framework import serializers from api import models class ViewSerializer(serializers.ModelSerializer): class Meta: model = models.Role fields = "__all__"
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)
三、GenericViewSet.net
繼承了ViewSetMixin和GenericAPIView3d
from django.conf.urls import url from api import views urlpatterns = [ url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view({'get': 'list'})), ]
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)
四、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'})), ]
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 # 分頁類
五、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'})), ]
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 # 分頁類
六、當使用GenericViewSet類時,會執行它父類GenericAPIView裏面的get_object方法,這個方法執行了check_object_permissions方法來對對象的權限進行校驗:
3、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)), ]
自動生成的路由:
能夠經過http://127.0.0.1:8080/api/v2/role/ http://127.0.0.1:8080/api/v2/role.json等方式進行訪問
4、rest framework的渲染器
一、局部配置
urlpatterns = [ url(r'^(?P<version>[v1|2]+)/test/$', views.TestView.as_view()), ]
from rest_framework import serializers from api import models class ViewSerializer(serializers.ModelSerializer): class Meta: model = models.Role fields = "__all__"
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)
二、全局配置
在項目的settings裏面: