rest_framework-版本-总结完结篇
Posted liang-jc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rest_framework-版本-总结完结篇相关的知识,希望对你有一定的参考价值。
总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 from rest_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-版本-总结完结篇的主要内容,如果未能解决你的问题,请参考以下文章