Django - DRF - 版本控制(配合路由的反向解析獲取連結)
阿新 • • 發佈:2018-12-29
目錄
1-1 URLPathVersioning - 基於url的正則方式:/v1/users/
1-2 QueryParameterVersioning - 基於url的get 傳參方式:/users?version=v1
1-3 AcceptHeaderVersioning - 基於請求頭方式:Accept: application/json; version=1.0
1-4 HostNameVersioning - 基於主機名:v1.example.com
1-5 NamespaceVersioning - 基於路由系統:example.com/v1/users/
2-1 區域性配置 - CBV內 versioning_class
一、版本控制 - 用於控制路由的版本跳轉
1-1 URLPathVersioning - 基於url的正則方式:/v1/users/
1-1-1 路由配置
from django.conf.urls import url,include from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^(?P<version>[v1|v2|v3]+)/books/$', views.Book.as_view({'get':'get_all'}),name='ttt'), ]
1-1-2 檢視函式
from rest_framework.pagination import CursorPagination from rest_framework.versioning import URLPathVersioning class Book(ViewSetMixin, APIView): versioning_class = URLPathVersioning def get_all(self, request,*args,**kwargs): # 版本可以從request.version內調取 print(request.version) # django 的路由反向解析 # from django.urls import reverse # url2=reverse(viewname='ttt',kwargs={'version':request.version}) # print(url2) # 提供給咱的解析 url2=request.versioning_scheme.reverse('ttt',request=request) print(url2) book_list = models.Book.objects.all() # 例項化產生一個加密分頁物件 page = CursorPagination() page.ordering = 'nid' page.page_size=2 page_list = page.paginate_queryset(book_list, request, self) ser = mySer.BookSerializer(instance=page_list, many=True) return page.get_paginated_response(ser.data)
1-1-3 setting配置
REST_FRAMEWORK = { 'VERSION_PARAM': 'version', 'DEFAULT_VERSION': 'v1', 'ALLOWED_VERSIONS': ['v1', 'v2'], }
1-2 QueryParameterVersioning - 基於url的get 傳參方式:/users?version=v1
1-1-1 路由設計
from django.conf.urls import url,include from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^books/', views.Book.as_view({'get':'get_all'}),name='ttt'), ]
1-1-2 setting配置
REST_FRAMEWORK = { 'VERSION_PARAM': 'version', 'DEFAULT_VERSION': 'v1', 'ALLOWED_VERSIONS': ['v1', 'v2'], }
1-1-3 檢視函式
1-3 AcceptHeaderVersioning - 基於請求頭方式:Accept: application/json; version=1.0
1-4 HostNameVersioning - 基於主機名:v1.example.com
1-5 NamespaceVersioning - 基於路由系統:example.com/v1/users/
二、使用配置
2-1 區域性配置 - CBV內 versioning_class
2-2 全域性配置 - setting配置
REST_FRAMEWORK = { # 'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning', 'VERSION_PARAM':'version', # get傳輸時候的key名,必須和有名分組的名字相對應 'DEFAULT_VERSION':'v1', # 預設版本 'ALLOWED_VERSIONS': ['v1', 'v2'], # 可選擇的版本 }