• Django REST Framework


    Django REST Framework  - 版本控制

    为什么需要版本控制? 

      API 版本控制允许我们在不同的客户端之间更改行为(同一个接口的不同版本会返回不同的数据)。 DRF提供了许多不同的版本控制方案。

      可能会有一些客户端因为某些原因不再维护了,但是我们后端的接口还要不断的更新迭代,这个时候通过版本控制返回不同的内容就是一种不错的解决方案。

    DRF提供的版本控制的方案

      DRF提供了5种版本控制方案, 如下图:

    版本控制系统的使用>>>>>>>>>>>>>>>>>.

      全局配置>>>

      

    这里我们以 URLPathVersioning 为例,还是在项目的settings.py中REST_FRAMEWORK配置项下配置:

    /v1/books/

    复制代码
    REST_FRAMEWORK = {
        'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
        'DEFAULT_VERSION': 'v1',  # 默认的版本
        'ALLOWED_VERSIONS': ['v1', 'v2'],  # 有效的版本
        'VERSION_PARAM': 'version',  # 版本的参数名与URL conf中一致
    }
    复制代码

    /books/?version=v1

    REST_FRAMEWORK = {
        'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.QueryParameterVersioning',
        'DEFAULT_VERSION': 'v1',  # 默认的版本
        'ALLOWED_VERSIONS': ['v1', 'v2'],  # 有效的版本
        'VERSION_PARAM': 'version',  # 版本的参数名与URL conf中一致
    }

    urls.py中

    复制代码
    urlpatterns = [
        ...
        url(r'^(?P<version>[v1|v2]+)/publishers/$', views.PublisherViewSet.as_view({'get': 'list', 'post': 'create'})),
        url(r'^(?P<version>[v1|v2]+)/publishers/(?P<pk>d+)/$', views.PublisherViewSet.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
    
    ]
    复制代码

    我们在视图中可以通过访问 request.version 来获取当前请求的具体版本,然后根据不同的版本来返回不同的内容:

    我们可以在视图中自定义具体的行为,下面以不同的版本返回不同的序列化类为例

    复制代码
    class PublisherViewSet(ModelViewSet):
    
        def get_serializer_class(self):

    """不同的版本使用不同的序列化类"""

            if self.request.version == 'v1':
                return PublisherModelSerializerVersion1
            else:
                return PublisherModelSerializer
        queryset = models.Publisher.objects.all()

     

    局部配置  

      注意,通常我们是不会单独给某个视图设置版本控制的,如果你确实需要给单独的视图设置版本控制,你可以在视图中设置versioning_class属性,如下

    class PublisherViewSet(ModelViewSet):
    
        ...
        versioning_class = URLPathVersioning

    源码分析:

      request.verysion 都经历了什么?

      版本控制能做什么?

     

     

  • 相关阅读:
    POJ3690:Constellations(二维哈希)
    Codeforces Round #547 (Div. 3) 题解
    Educational Codeforces Round 48 (Rated for Div. 2) CD题解
    Educational Codeforces Round 50 (Rated for Div. 2) C. Classy Numbers
    Codeforces Round #508 (Div. 2) E. Maximum Matching(欧拉路径)
    Codeforces Round #546 (Div. 2) 题解
    Codeforces Round #545 (Div. 2) 题解
    Codeforces Round #544 (Div. 3) 题解
    利用最新Apache解析漏洞(CVE-2017-15715)绕过上传黑名单
    xctf一道反序列化题
  • 原文地址:https://www.cnblogs.com/konghui/p/10274049.html
Copyright © 2020-2023  润新知