DRF版本控制(源码分析)

DRF中版本控制的五种情况(源码分析)

在restful规范中要去,后端的API中需要体现版本。

drf框架中支持5种版本的设置。

1. URL的GET参数传递(*)

示例: user/?version=v1

# settings.py

REST_FRAMEWORK = {
    "VERSION_PARAM": "v",
    "DEFAULT_VERSION": "v1",
    "ALLOWED_VERSIONS": ["v1", "v2", "v3"],
    "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.QueryParameterVersioning"
}

源码执行流程:

  1. 图解: 两部分

2.URL路径传递(*)

示例: /api/v1/user

# urls.py

urlpatterns = [
    path('api/<str:version>/user', views.UserView.as_view()),
]
# settings.py

REST_FRAMEWORK = {
    "VERSION_PARAM": "v",
    "DEFAULT_VERSION": "v1",
    "ALLOWED_VERSIONS": ["v1", "v2", "v3"],
    "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning"
}

3.请求头传递

# settings.py

REST_FRAMEWORK = {
    "VERSION_PARAM": "v",
    "DEFAULT_VERSION": "v1",
    "ALLOWED_VERSIONS": ["v1", "v2", "v3"],
    "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.AcceptHeaderVersioning"
}

ps: 可以使用postman伪造请求. 设置请求头: Accept : application/json; version=v3

4.二级域名传递

示例: v1.xxx.com/api/user

# settings.py

REST_FRAMEWORK = {
    "VERSION_PARAM": "v",
    "DEFAULT_VERSION": "v1",
    "ALLOWED_VERSIONS": ["v1", "v2", "v3"],
    "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.HostName"
}

在使用二级域名这种模式时需要先做两个配置:

  • 域名需解析至IP,本地可以在hosts文件中添加

    127.0.0.1       v1.wupeiqi.com
    127.0.0.1       v2.wupeiqi.com
    
  • 在django的settings.py配置文件中添加允许域名访问

    ALLOWED_HOSTS = ["*"]
    

5.路由的namespace传递

反向生成url:

# urls.py

urlpatterns = [
    path('api/user', views.UserView.as_view(), name='n1'),
    path('api/user/<int:pk>', views.UserView.as_view(), name='n2'),
]
# views.py

from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response

# Create your views here.
class UserView(APIView):
	def get(self, request, *args, **kwargs):
		request.versioning_scheme.reverse('n1', request=request)
		request.versioning_scheme.reverse('n2', args=(11, ), request=request)
	return Response({'code': 0, 'data': '嘻嘻嘻哈啊哈哈'})

	def post(self, request, *args, **kwargs):
		pass


小结

以后使用drf开发后端API接口时:

  1. 创建django程序
  2. 安装drf框架
  3. 创建一个app专门来处理用户的请求
  4. 注册APP -> app 和 drf配置
  5. 设置版本
  6. 编写视图类

posted on 2023-04-17 00:06  huxiaofeng  阅读(70)  评论(0编辑  收藏  举报

导航