四、版本控制


返回

4.1 自定义版本控制类

  • settings.py

    # DRF配置
    REST_FRAMEWORK = {
        "DEFAULT_VERSIONING_CLASS": "utils.version.MyVersion",
    }
    
    
  • utils/version.py:自定义版本控制类的determine_version方法

    class MyVersion(object):
        """ 自定义的版本控制类 """
    
        def determine_version(self, request, *args, **kwargs):
            """
            版本号携带在过滤条件 url?version=v1
            :param request: 
            :param args: 
            :param kwargs: 
            :return: 版本号 给了request.version
            """
            version = request.query_params.get("version", "v1")
    
            return version
    
    

4.2 利用框架

  • 提供了五种常用的版本配置类

    from rest_framework.versioning import NamespaceVersioning
    from rest_framework.versioning import HostNameVersioning
    from rest_framework.versioning import URLPathVersioning
    from rest_framework.versioning import AcceptHeaderVersioning
    from rest_framework.versioning import QueryParameterVersioning
    
  • 如:settings.py

    # DRF配置
    REST_FRAMEWORK = {
        "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.QueryParameterVersioning",
        "DEFAULT_VERSION": "v1",
        "ALLOWED_VERSIONS": "v1, v2",
        "VERSION_PARAM": "version"
    }
    
    
返回