总urls.py
from django.conf.urls import url, includeurlpatterns = [ url(r'^api/', include('api.urls'))]
分流后urls.py
from django.conf.urls import urlfrom api import viewsurlpatterns = [ url(r'^(?P[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, HttpResponsefrom rest_framework.views import APIViewfrom rest_framework.versioning import QueryParameterVersioning,URLPathVersioningfrom 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')