Python之Django rest_Framework(3)

補充:前端

 爲何要先後端分離:django

      a、由於前端它有本身框架,這樣它的效率就很是高json

      b、不作先後端分離,公司若是既有客戶端,又有app這種狀況下你就的寫兩遍後端

django restful框架好處:api

      幫助咱們寫了好多組件好比:緩存

      a、認證:有類,類中的方法authenticate/authenticate_header,它的返回值有None,元組,異常。若是返回值爲None那就無論,它是匿名用戶。restful

      b、權限:有類,類中的方法:has_permissionapp

      c、節流:有類,類的方法:allow_request,在這裏allow_request來表示限制,它是經過IP來限制,框架

                      它的內部原理是:默認是IP,用戶來用IP,這個IP可能代理IP,IP或者是代理IP拿着請求頭默認放到你們可以的緩存中                          去,每個人的IP爲p,後面的那個列表存它的方位時間,每一次請求進來獲取它的當前時間根據時間的個數來比較,在                        比較的過程當中看看把不符合時間的個數來進行比較,能訪問就繼續,不能訪問就不要繼續。前後端分離

      d、版本:是url和hostname,他們兩個鍾每個都有兩個方法一個是幫你拿版本另外一個是幫你反向生成url

      e、解析器:用戶發過來的請求體數據進行操做

      f、序列化:兩個功能:序列化,校驗

1、分頁

分頁的三種狀況:

       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

 

2、視圖

一、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)

二、GenericAPIview(APIView)

三、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

四、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]

相關文章
相關標籤/搜索