在restful規範中要去,後端的API中需要體現版本。
drf框架中支援5種版本的設定。
範例: 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"
}
原始碼執行流程:
範例: /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"
}
# 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
範例: 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 = ["*"]
反向生成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介面時:
本文來自部落格園,作者:{Max},僅供學習和參考