作用
因为程序在不停的更新迭代,新版和旧版差别比较大,但此时有些用户没用进行更新,还是访问的旧版,此时就需要进行版本控制,让用户体验更好
内置版本控制
from rest_framework.versioning import QueryParameterVersioning, AcceptHeaderVersioning, NamespaceVersioning, URLPathVersioning, HostNameVersioning
"""
1. QueryParameterVersioning: 基于url的get传参方式, 如: /users?version=v1
2. URLPathVersioning: 基于url的正则方式, 如: /v1/users/
3. AcceptHeaderVersioning: 基于accept请求头方式, 如: Accept: application/json; version=1.0
4. HostNameVersioning: 基于主机名方法, 如: v1.example.com
5. NamespaceVersioning: 基于django路由系统的namespace, 如: example.com/v1/users/
"""
局部使用
只需要在CBV函数中加入如下参数:
versioning_class = URLPathVersioning
全局使用
需要在settings.py中进行配置
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.QueryParameterVersioning',
'DEFAULT_VERSION': 'v1', # 默认版本(从request对象里取不到,显示的默认值)
'ALLOWED_VERSIONS': ['v1', 'v2'], # 允许的版本
'VERSION_PARAM': 'version' # URL中获取值的key
}
案例
基于正则的方式:
# urls.py
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'),
]
# views.py
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)