「Django」rest_framework学习系列-版本认证

1.自己写:

class UserView(APIView):
versioning_class = ParamVersion
    def get(self,request,*args,**kwargs):
        v1 = request._request.GET.get('version')
        v2 = request.query_params.get('version')
        #获取结果是一样的,两种获取方式
        print(v1,v2)  
View Code

2.使用自带类:

from rest_framework.versioning import BaseVersioning
class ParamVersion(BaseVersioning):
    def determine_version(self, request, *args, **kwargs):
        version = request.query_params.get('version')
        return version
class UserView(APIView):
    versioning_class = ParamVersion
    def get(self,request,*args,**kwargs):
        v=request.version
        print(v)    

3.使用类方法,不用写:

from rest_framework.versioning import QueryParameterVersioning
class UserView(APIView):
    versioning_class = QueryParameterVersioning
    def get(self,request,*args,**kwargs):
        v=request.version
        print(v)
settings中编写默认配置:
REST_FRAMEWORK = {
'DEFAULT_VERSION':'v1', 默认版本
'ALLOWED_VERSIONS':['v1','v2'], 允许版本
'VERSION_PARAM':'version', 前端传参,可以写v
}
View Code

4.URL读取版本:

全局配置:
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning',
URLS配置:
re_path(r'^(?P<version>[v1|v2]+)/userview/$',UserView.as_view())
v1,v2要遵循默认的版本配置
View Code

5.反向生成url:

def get(self,request,*args,**kwargs):
    v=request.version        url=request.versioning_scheme.reverse(viewname='uuu',request=request)
    print(v,url)
urls配置:
re_path(r'^(?P<version>[v1|v2]+)/userview/$',UserView.as_view(),name='uuu')
View Code
posted @ 2019-02-19 17:39  子谦0618  阅读(117)  评论(0编辑  收藏  举报