from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.versioning import BaseVersioning,URLPathVersioning # Introduce here
class VersionView(APIView):
versioning_class = URLPathVersioning # Use here , Note that this is not a list of classes , It's just one. ,.
def get(self,request, *args, **kwargs):
print(request.version) # Get version
print(request.versioning_scheme) # Get version of object
url = request.versioning_scheme.reverse(viewname='xxx', request=request) # Used for reverse generation url
print(url) # According to the preceding url.py In is the setting , Here is the generation of : http://127.0.0.1:8000/api/v1/
return HttpResponse('hello world')
2, urls.py Below :
from django.contrib import admin
from django.urls import re_path, path
from django.conf.urls import url, include
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/(?P<version>[v1|v2]+)/$', views.VersionView.as_view(), name='xxx')
]