6. DRF 版本
目录
Django DRF 版本
1. 使用
rest_framework 的 versioning.py中定义了多种方法,支持不同方式携带version信息,
比如支持url/hostname/namespace中携带并传递version信息
1.1 URL 参数传递version
https://127.0.0.1:8000/user/?version=v1
1.1.1基于单视图
class Home2(APIView):
from rest_framework.versioning import QueryParameterVersioning
throttle_classes = [MineThrottle]
permission_classes = [MinePermission, MinePermission1, MinePermission2]
versioning_class = QueryParameterVersioning
def check_permissions(self, request):
permission_result = []
for permission in self.get_permissions():
permission_result.append(permission.has_permission(request, self))
if True not in permission_result:
self.permission_denied(
request,
message=getattr(permission, 'message', None),
code=getattr(permission, 'code', None)
)
def get(self, reqeust):
return JsonResponse({"status": True, 'data': 'OK'})
def post(self, request):
print(request.user, request.auth)
return JsonResponse({"status": True, 'data': 'OK'})
1.1.2 全局配置
settings.py中配置
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ['utils.auth.Myauth'],
"DEFAULT_PERMISSION_CLASSES": ['utils.permission.MinePermission'],
"DEFAULT_THROTTLE_CLASSES": ['utils.throttle.MineThrottle'],
"DEFAULT_THROTTLE_RATES": {
"user": "5/m"
},
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.QueryParameterVersioning"
}
1.1.3 使用
请求url: http://127.0.0.1:8000/home2/?version=v1, 现在就能通过request.version拿到版本信息
1.2 URL 地址传递version
http://127.0.0.1:8000/v2/home2/
1.2.1 使用
settings.py中修改
REST_FRAMEWORK = {
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning"
}
urls.py中定义 url
from django.urls import path
from app001 import views
urlpatterns = [
# path('admin/', admin.site.urls),
path('home/', views.home),
path('demo/', views.demo),
path('<str:version>/home2/', views.Home2.as_view()),
path('login/', views.Login.as_view())
]
现在就能获取到request.version
1.3 请求头传递version
settings.py中修改
REST_FRAMEWORK = {
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.AcceptHeaderVersioning"
}
2. 源码分析
请求进到DRF会先经过 drf的dispatch方法
scheme = self.versioning_class()
return (scheme.determine_version(request, *args, **kwargs), scheme)
比如versioning_class 定义的是 rest_framework.versioning.QueryParameterVersioning
那么返回值就是 先实例化rest_framework.versioning.QueryParameterVersioning 再执行方法
rest_framework.versioning.QueryParameterVersioning().determine_version(request, *args, **kwargs)