Analysis of Django interface version control

Time:2022-5-14
catalogue
  • 1、 Foreword
  • 2、 Disposition
    • 2.1. Global configuration
    • 2.2. View configuration
  • 3、 Five version control classes built in DRF
    • 3.1、AcceptHeaderVersioning
      • 3.1.1. HTTP access method
      • 3.1.2、settings
      • 3.1.3、serializers
      • 3.1.4、views
      • 3.1.5 access
    • 3.2、URLPathVersioning
      • 3.2.1. HTTP access method
      • 3.2.2、settings
      • 3.2.3、urls
      • 3.2.4 access
    • 3.3、NamespaceVersioning
      • 3.3.1. HTTP access method
      • 3.3.2、settings
      • 3.3.3、urls
      • 3.3.4 access

1、 Foreword

stayRESTfulIn the specification, for problems related to version, userestfulWhen the specification makes an open interface, the user requestsAPI, the system returns data. However, in the process of system development, it is inevitable to add new resources or modify existing resources. Therefore, changes and upgrades are essential. However, as a platform developer, you should know that onceAPIAfter opening up, someone began to use it. Any change to the platform needs to consider the impact on current users. Therefore, make an open platform from the firstAPIYour design needs to startAPIVersion control policy issues,APIThe version control strategy of is like a long-term agreement between the open platform and platform users. Its design will directly determine whether users use the platform, or whether users will directly abandon the platform because of a version upgrade.

2、 Disposition

There are two configuration schemes, one is insettingsThe second is to specify in the view, butThis method is generally not usedBecause version control is a global process in most cases

2.1. Global configuration

settings.py


REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': None,
    'DEFAULT_VERSION': None,
    'ALLOWED_VERSIONS': None,
    'VERSION_PARAM': 'version',
}
  • DEFAULT_ VERSIONING_ Class: Specifies the version control class, for example: ‘rest’_ framework. versioning. Namespace versioning ‘, there are many ways. The default is none. When it is none, the frame variable request Version will always return none
  • DEFAULT_ Version: used to set request when version control information does not exist The default value of version is none by default.
  • ALLOWED_ Versions: allowed version number, for example: [‘v1 ‘,’ V2 ‘]. Case sensitive. If the requested version number is not in this list, an error will be thrown, and the above default_ The value of version must be the value in the list, except none
  • VERSION_ Param: the string of version control parameters. The default is version. It is generally not modified

2.2. View configuration

views.py

#Specify only version control classes    
class ProfileList(APIView):
    #Specify version control class
    versioning_class = versioning.QueryParameterVersioning

3、 Five version control classes built in DRF

3.1、AcceptHeaderVersioning

Version control based on request header is also the most recommended method

3.1.1. HTTP access method

GET /bookings/ HTTP/1.1

Host: example.com

Accept: application/json; version=1.0

In the example request aboverequest.versionProperty will return the string ‘1.0’. be based onaccept headers Versioning is often considered a best practice, although other versioning methods may suit your client needs.

3.1.2、settings


REST_FRAMEWORK = {
	'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],
}

explain:

  • Set version control class toAcceptHeaderVersioning
  • Not detectedversionThe default isv1edition
  • The two versions allowed are:['v1', 'v2']

3.1.3、serializers


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ['title', 'pub_date', 'read', 'comment', 'image']


class BookSerializerV2(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ['title', 'pub_date', 'read', 'comment']

explain:

  • According to different version numbers, you canresponseReturn content for control, we set 2 differentBookModelledserializerClass corresponds to different versions
  • The fields returned by the two serialization classes are different
  • BookSerializerV2offieldsNot included inimage, then the attribute definition should be removed, or an error will be thrown

3.1.4、views


class BookView(ListAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer

    def get_serializer_class(self):
        if self.request.version == "v2":
            return BookSerializerV2
        return self.serializer_class

explain:

  • modifyBookViewClass, overloadingget_serializer_classmethod
  • adoptself.request.version Get the captured version number for control

3.1.5 access

We add fields to the request headerAccept:application/json;version=v1, it will returnBookSerializerSerialized fields, that is, there areimagefield

We add fields to the request headerAccept:application/json;version=v2, it will returnBookSerializerV2Serialized fields, that is, noimagefield

3.2、URLPathVersioning

This scenario requires the client to specify the version as part of the URL path.

3.2.1. HTTP access method

GET /v1/bookings/ HTTP/1.1

Host: example.com

Accept: application/json

explain:

Version control appears inurlIn the path, but the specific one v1Which part appears depends onurlSituation in routing configuration

3.2.2、settings


REST_FRAMEWORK = {
	'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],
}

3.2.3、urls

URLs for subapplications Py:


urlpatterns = [
    path('<str:version>/books/', views.BookView.as_view()),
]

explain:

Set version control at the end, accessurlIs similar to:http://127.0.0.1:8000/api/v2/books/

3.2.4 access

We’re configuringurlAfter, inurlIf you enter V1 in, you will access the V1 version of the interface

stayurlIf you enter V2 in, you will access the V2 version of the interface

3.3、NamespaceVersioning

For clients, this scheme is similar toURLPathVersioningSame. The only difference is how it worksDjangoConfigured in the application because it usesURL confNamespace in instead ofURL confKeyword parameters in.

Using this scheme,request.versionProperty is based on the path that matches the incoming requestnamespaceaffirmatory.

If you only need a simple version control schemeURLPathVersioningandNamespaceVersioningAre appropriate.URLPathVersioningThis approach may be more suitable for small projects and for larger projectsNamespaceVersioningIt may be easier to manage.

3.3.1. HTTP access method

GET v1/something/ HTTP/1.1

Host: example.com

3.3.2、settings


REST_FRAMEWORK = {
	'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],
}

3.3.3、urls

Root URLs Py:


urlpatterns = [
    path('v1/api/', include('api.urls', namespace='v1')),
    path('v2/api/', include('api.urls', namespace='v2')),
]

explain:

Added 2v1andv2Different routing configurations

3.3.4 access

visitv1edition

visitv2edition

restHostNameVersioningandQueryParameterVersioningI don’t use much. If you want to know, you can check the official documents

The above is the detailed analysis of Django interface version control. For more information about Django interface version control, please pay attention to other relevant articles of developeppaer!