请求进来 封装request. 版本限制 认证 权限 节流 版本 self.version_param url中版本的key self.default_version self.is_allowed_version 都是写在配置文件中 如果是默认就是?version= reverse 获取版本 print(request.version) 获取处理版本的对象 print(request.versioning_scheme) REST_FRAMEWORK = { "DEFAULT_VERSION":'v1', "ALLOWED_VERSIONS": ['v1','v2'] , "VERSION_PARAM":'version', } URL中通过get的方式获取 自定义 from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from rest_framework.request import Request # Create your views here. class ParamVersion(object): def determine_version(self, request, *args, **kwarags): version = request.query_params.get('version') return version class UsersView(APIView): versioning_class = ParamVersion def get(self,request, *args, **kwargs): # version = request._request.GET.get('version') # print(version) print(request.version) return HttpResponse('用户列表') 在路径中传参 常用方式 views.py from django.shortcuts import render,HttpResponse from rest_framework.versioning import QueryParameterVersioning,URLPathVersioning class UsersView(APIView): versioning_class = URLPathVersioning def get(self,request, *args, **kwargs): print(request.version) return HttpResponse('用户列表') cmdb 下的 urls.py from django.conf.urls import url,include from cmdb import views urlpatterns = [ url(r'^(?P<version>[v1|v2]+)/users/$',views.UsersView.as_view()) ] 全局使用时 推荐使用的方式 setting文件 REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning" "DEFAULT_VERSION":'v1', "ALLOWED_VERSIONS": ['v1','v2'] , "VERSION_PARAM":'version', } views.py文件 from django.shortcuts import render,HttpResponse class UsersView(APIView): def get(self,request, *args, **kwargs): print(request.version) return HttpResponse('用户列表') urls.py文件 cmdb下的 urlpatterns = [ url(r'^(?P<version>[v1|v2]+)/users/$',views.UsersView.as_view()) ] 总结: 使用: 配置文件: REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning" "DEFAULT_VERSION":'v1', "ALLOWED_VERSIONS": ['v1','v2'] , "VERSION_PARAM":'version', } 路由系统 urlpatterns = [ url(r'^(?P<version>[v1|v2]+)/users/$',views.UsersView.as_view()) ] 主路由 from django.conf.urls import url,include urlpatterns = [ path('admin/', admin.site.urls), url(r'^cmdb/',include('cmdb.urls')) ] 视图中 from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from django.urls import reverse from rest_framework.request import Request # Create your views here. class UsersView(APIView): #反向生成URL def get(self,request, *args, **kwargs): #获取版本 print(request.version) #获取处理版本的对象 print(request.versioning_scheme) #通过rest_framework反向生成URL u1 = request.versioning_scheme.reverse(viewname='user',request=request) print(u1) #通过原生Django反向生成URL u2 = reverse(viewname='user',kwargs={'version':1}) print(u2) return HttpResponse('用户列表')