Django Rest Framework --- 版本控制组件

一、版本控制的作用

  开发阶段,一套网站的接口可能不止一套,因此需要在客户端请求时明确版本,版本控制组件就是解决这个问题的。

二、DRF内置的版本控制类

from rest_framework.versioning import QueryParameterVersioning,AcceptHeaderVersioning,NamespaceVersioning,URLPathVersioning

#基于url的get传参方式:QueryParameterVersioning------>如:/users?version=v1
#基于url的正则方式:URLPathVersioning------>/v1/users/
#基于 accept 请求头方式:AcceptHeaderVersioning------>Accept: application/json; version=1.0
#基于主机名方法:HostNameVersioning------>v1.example.com
#基于django路由系统的namespace:NamespaceVersioning------>example.com/v1/users/

三、版本控制类的使用方式

局部使用:在需要使用版本控制的视图类中加入变量versioning_class = 版本控制的类

#在CBV类中加入
versioning_class = URLPathVersioning

全局使用:在settings.py配置文件中的REST_FRAMEWORK中加上如下语句(不支持url中传值的版本控制方)

REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.QueryParameterVersioning',
    'DEFAULT_VERSION': 'v1',            # 默认版本(从request对象里取不到,显示的默认值)
    'ALLOWED_VERSIONS': ['v1', 'v2'],   # 允许的版本
    'VERSION_PARAM': 'version'          # URL中获取值的key
}

四、基于正则的版本控制示例

  • urls.py
"""versioning URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01.views import VersionTest

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^(?P<version>[v1|v2]+)/VersionTest/$', VersionTest.as_view(),name='test'),
]
  • views.py
from django.shortcuts import render,HttpResponse

# Create your views here.
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView
from rest_framework.response import Response
class VersionTest(APIView):
    versioning_class = URLPathVersioning
    def get(self,request,*args,**kwargs):

        version = request.version
        print(version)  #版本号
        version_class = request.versioning_scheme  #获取版本管理的类
        print(version_class)
        reverse_url = request.versioning_scheme.reverse('test', request=request)  #反向生成url
        print(reverse_url)
        return Response()

 

posted on 2019-04-01 17:21  黑粥  阅读(119)  评论(0编辑  收藏  举报

导航