用於版本的控制python
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/
#在CBV類中加入 versioning_class = URLPathVersioning
REST_FRAMEWORK = { 'DEFAULT_VERSIONING_CLASS':'rest_framework.\ versioning.QueryParameterVersioning', # 默認版本(從request對象裏取不到,顯示的默認值) 'DEFAULT_VERSION': 'v1', # 容許的版本 'ALLOWED_VERSIONS': ['v1', 'v2'], # URL中獲取值的key 'VERSION_PARAM': 'version' }
基於正則的方式:web
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^(?P<version>[v1|v2]+)/test/', TestView.as_view(), name='test'), ]
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.versioning import URLPathVersioning class TestView(APIView): versioning_class = URLPathVersioning def get(self, request, *args, **kwargs): # 獲取版本 print(request.version) # 獲取版本管理的類 print(request.versioning_scheme) # 反向生成URL reverse_url = request.versioning_scheme.reverse('test', request=request) print(reverse_url) return Response('GET請求,響應內容')
# 基於django內置,反向生成url from django.urls import reverse url2=reverse(viewname='ttt',kwargs={'version':'v2'}) print(url2)
# 執行determine_version,返回兩個值,放到request對象裏 version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme def determine_version(self, request, *args, **kwargs): #當配置上版本類以後,就會實例化 if self.versioning_class is None: return (None, None) scheme = self.versioning_class() return (scheme.determine_version(request, *args, **kwargs), scheme)