• Restful framework【第十二篇】版本控制


    简单使用

    -drf版本控制
      -在setting中配置
    	'DEFAULT_VERSION': 'v1',  # 默认版本(从request对象里取不到,显示的默认值)
    	'ALLOWED_VERSIONS': ['v1', 'v2'],  # 允许的版本
    	'VERSION_PARAM': 'version'  # URL中获取值的key
      -局部使用
    	versioning_class = URLPathVersioning
      -全局使用
    	'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning',

    内置的版本控制类

    from rest_framework.versioning import QueryParameterVersioning,AcceptHeaderVersioning,NamespaceVersioning,URLPathVersioning
    
    #基于url的get传参方式:QueryParameterVersioning------>如:/users?version=v1
    #基于url的正则方式:URLPathVersioning------>/v1/users/
    #基于 accept 请求头方式:AcceptHeaderVersioning------>Accept: application/json; version=1.0
    #基于主机名方法:HostNameVersioning------>v1.example.com
    #基于django路由系统的namespace:NamespaceVersioning------>example.com/v1/users/

    局部使用

    #在CBV类中加入
    versioning_class = URLPathVersioning

    全局使用

    REST_FRAMEWORK = {
        'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.QueryParameterVersioning',
        'DEFAULT_VERSION': 'v1',            # 默认版本(从request对象里取不到,显示的默认值)
        'ALLOWED_VERSIONS': ['v1', 'v2'],   # 允许的版本
        'VERSION_PARAM': 'version'          # URL中获取值的key
    }

    示例

    基于正则的方式:

    url

    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)
  • 相关阅读:
    Network(树形dp)洛谷2899
    2590 树的统计
    LCT 最小生成树
    几种贪心小结
    snmp
    div页面跳转
    2017.11.2总结,回顾及成果
    2017.11.1知识总结及回顾
    check,form,单选框与复选框总结
    HTML空格字符
  • 原文地址:https://www.cnblogs.com/596014054-yangdongsheng/p/10403035.html
Copyright © 2020-2023  润新知