rest_framework-版本-總結完結篇
阿新 • • 發佈:2018-07-30
sch versions return col args 視圖 scheme views color
總urls.py
from django.conf.urls import url, include urlpatterns = [ url(r‘^api/‘, include(‘api.urls‘)) ]
分流後urls.py
from django.conf.urls import url from api import views urlpatterns = [ url(r‘^(?P<version>[v1|v2]+)/user/$‘, views.UserView.as_view(),name=‘us‘) ]
settings.py
REST_FRAMEWORK = {"DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning", "DEFAULt_VERSION":‘v1‘, #默認為1 "ALLOWED_VERSIONS":[‘v1‘,‘v2‘], #僅允許v1或者v2訪問 "VERSION_PARAM":‘version‘, }
views.py 視圖
from django.shortcuts import render, HttpResponse from rest_framework.views import APIView fromrest_framework.versioning import QueryParameterVersioning,URLPathVersioning from django.urls import reverse # Create your views here. class UserView(APIView): def get(self, request, *args, **kwargs): #獲取版本 print(request.version) #獲取處理版本的對象 print(request.versioning_scheme) #反向生成URL(rest_framework) u1= request.versioning_scheme.reverse(viewname=‘us‘,request=request) print(u1) u2 = reverse(viewname=‘uuu‘, kwargs={‘version‘:1212}) print(u2) return HttpResponse(‘ok‘)
rest_framework-版本-總結完結篇