Python之Django rest_Framework(3)

补充:

 为什么要前后端分离:

      a、因为前端它有自己框架,这样它的效率就非常高

      b、不做前后端分离,公司如果既有客户端,又有app这种情况下你就的写两遍

django restful框架好处:

      帮助我们写了好多组件比如:

      a、认证:有类,类中的方法authenticate/authenticate_header,它的返回值有None,元组,异常。如果返回值为None那就不管,它是匿名用户。

      b、权限:有类,类中的方法:has_permission

      c、节流:有类,类的方法:allow_request,在这里allow_request来表示限制,它是通过IP来限制,

                      它的内部原理是:默认是IP,用户来用IP,这个IP可能代理IP,IP或者是代理IP拿着请求头默认放到大家能够的缓存中                          去,每一个人的IP为p,后面的那个列表存它的方位时间,每一次请求进来获取它的当前时间根据时间的个数来比较,在                        比较的过程中看看把不符合时间的个数来进行比较,能访问就继续,不能访问就不要继续。

      d、版本:是url和hostname,他们两个钟每一个都有两个方法一个是帮你拿版本另一个是帮你反向生成url

      e、解析器:用户发过来的请求体数据进行操作

      f、序列化:两个功能:序列化,校验

一、分页

分页的三种情况:

       a、记录当前访问页的数据id

       b、最多显示120页

       c、对页码进行加密

a、基于limit offset做分页

class P1(LimitOffsetPagination):
    
                max_limit = 3
                default_limit = 2
                limit_query_param = 'limit'
                offset_query_param = 'offset'
                        
            
            class IndexView(views.APIView):
                def get(self,request,*args,**kwargs):
                    user_list = models.UserInfo.objects.all()
                    p1 = P1()
                    page_user_list = p1.paginate_queryset(queryset=user_list, request=request, view=self)
                    ser = IndexSerializer(instance=page_user_list, many=True)
                    return Response(ser.data) # 不含上一页和下一页
                    # return p1.get_paginated_response(ser.data) # 含上一页和下一页
                    
            class IndexView(views.APIView):
                def get(self,request,*args,**kwargs):
                    ret = BaseResponse()
                    try:
                        user_list = models.UserInfo.objects.all()
                        p1 = P1()
                        page_user_list = p1.paginate_queryset(queryset=user_list,request=request,view=self)
                        ser = IndexSerializer(instance=page_user_list,many=True)
                        ret.data = ser.data
                        ret.next = p1.get_next_link()
                    except Exception as e:
                        ret.code= 1001
                        ret.error = 'xxxx错误'
                    return Response(ret.__dict__)

 b. 基于页码的分页

class P2(PageNumberPagination):
                # 每页显示的数据条数
                max_page_size = 5
                page_size = 2
                page_size_query_param = 'size'

                # 页码
                page_query_param = 'page'

c. 基于Cursor的分页

class P3(CursorPagination):
                cursor_query_param = 'cursor'
                page_size = 2
                ordering = 'id'

 

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

urlpatterns = [
    #url(r'^admin/', admin.site.urls),
    url(r'^api/(?P<version>[v1|v2]+)/', include('api.urls')),
]
url.py

 

REST_FRAMEWORK = {
    "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning",
    "VERSION_PARAM":'version',
    "ALLOWED_VERSIONS":['v1','v2'],
    'DEFAULT_VERSION':'v1',
    'PAGE_SIZE':2
}
setting.py
from django.shortcuts import render
from rest_framework import views
from rest_framework.response import Response
from rest_framework.pagination import LimitOffsetPagination

from api import models
from api.serializers.index import IndexSerializer

class BaseResponse(object):
    def __init__(self,code=1000,data=None,error=None):
        self.code = code
        self.data = data
        self.error = error

class P1(LimitOffsetPagination):

    max_limit = 3
    default_limit = 2
    limit_query_param = 'limit'
    offset_query_param = 'offset'



class IndexView(views.APIView):
    def get(self, request, *args, **kwargs):
        ret = BaseResponse()
        try:
            user_list = models.UserInfo.objects.all()
            p1 = P1()
            page_user_list = p1.paginate_queryset(queryset=user_list,request=request,view=self)
            ser = IndexSerializer(instance=page_user_list,many=True)
            ret.data = ser.data
            ret.next = p1.get_next_link()
        except Exception as e:
            ret.code= 1001
            ret.error = 'xxxx错误'

        return Response(ret.__dict__)
views.py
from django.conf.urls import url,include
from django.contrib import admin
from api import views
urlpatterns = [

    url(r'^index/$', views.IndexView.as_view()),
]
url.py 和views一个App 下的url

 

二、视图

1、APIView

class IndexView(views.APIView):
                    def get(self, request, *args, **kwargs):
                        user_list = models.UserInfo.objects.all()
                        ser = IndexSerializer(instance=user_list,many=True)
                        return Response(ser.data)

2、GenericAPIview(APIView)

3、GenericViewSet(ViewSetMixin,generics.GenericAPIView)

路由修改:
                    urlpatterns = [
                        url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})),
                        url(r'^index/(?P<pk>\d+)$', views.IndexView.as_view({'get':'retrieve'})),
                    ]
                
                视图修改:
                    
                    class IndexView(viewsets.GenericViewSet):

                        def list(self,request,*args,**kwargs):

                             pass # 获取列表信息

                        def retrieve(self, request, *args, **kwargs):
                            pass  # 获取单条数据

                        def create(self,request, *args, **kwargs):
                            pass
                
                
                自定义:
                    
                        增
                            POST
                            /users/
                        删
                            DELETE
                            /users/1/
                        改
                            PUT
                            /users/1/
                            
                            patch
                            /users/1/
                        查
                            GET
                            /users/ 
                            GET
                            /users/1/
                            
                        urlpatterns = [

                            url(r'^index/$', views.IndexView.as_view()),
                            url(r'^index/(?P<pk>\d+)$', views.IndexView.as_view()),
                        ]
                            
                        class IndexView(views.APIView):

                            def get(self,request,*args,**kwargs):
                                pk = kwargs.get('pk')
                                if pk:
                                    pass # 获取单条信息
                                else:
                                    pass # 获取列表信息

                            def post(self,request,*args,**kwargs):
                                pass

                            def put(self,request,*args,**kwargs):
                                pass

                            def patch(self,request,*args,**kwargs):
                                pass

                            def delete(self,request,*args,**kwargs):
                                pass

4、ModelViewSet

 

ModelViewSet(mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet)                
                
                class IndexView(ModelViewSet):

 

REST_FRAMEWORK = {
    "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning",
    "VERSION_PARAM":'version',
    "ALLOWED_VERSIONS":['v1','v2'],
    'DEFAULT_VERSION':'v1',
    # 'PAGE_SIZE':2
}
setting.py
from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    #url(r'^admin/', admin.site.urls),
    url(r'^api/(?P<version>[v1|v2]+)/', include('api.urls')),
]
url.py
from django.shortcuts import render
from rest_framework import views
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination,CursorPagination

from api import models
from api.serializers.index import IndexSerializer

class P2(PageNumberPagination):
        # 每页显示的数据条数
        max_page_size = 5
        page_size = 2
        page_size_query_param = 'size'

        # 页码
        page_query_param = 'page'

class IndexView(viewsets.ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = IndexSerializer
    pagination_class = P2
views
from django.conf.urls import url,include
from django.contrib import admin
from api import views
urlpatterns = [

    url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})),
    url(r'^index/(?P<pk>\d+)/$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
]
url.py 和views一个APP下的路由

3. 路由

第一类:

# http://127.0.0.1:8000/api/v1/auth/
url(r'^auth/$', views.AuthView.as_view()),
# http://127.0.0.1:8000/api/v1/auth.json # 想要让页面显示json格式
url(r'^auth\.(?P<format>[a-z0-9]+)$', views.AuthView.as_view()),
# http://127.0.0.1:8000/api/v1/auth/1/
url(r'^auth/(?P<pk>\d+)/$', views.AuthView.as_view()),
# http://127.0.0.1:8000/api/v1/auth/1.json
url(r'^auth/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)$', views.AuthView.as_view()),
class AuthView(views.APIView):

def get(self,request,*args,**kwargs):
return Response('...')

第二类:

url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})),
url(r'^index/\.(?P<format>[a-z0-9]+)$', views.IndexView.as_view({'get':'list','post':'create'})),
url(r'^index/(?P<pk>\d+)/$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
url(r'^index/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),

class IndexView(viewsets.ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = IndexSerializer
pagination_class = P2

第三类:

router = DefaultRouter()
router.register('index',views.IndexViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]


class IndexViewSet(viewsets.ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = IndexSerializer
pagination_class = P2



class IndexSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__"


4. 渲染器
看到的页面时什么样子的,返回数据。
renderer_classes = [JSONRenderer,BrowsableAPIRenderer]

posted @ 2018-02-08 17:39  孟庆健  阅读(251)  评论(0编辑  收藏  举报