Django REST framework
is a framework based on Django
, and REST framework
How is it? 反向生成url
?
In the previous example, you know that REST framework
there are 6 versioning methods in which you enter any version-controlled source code,
class Queryparameterversioning (baseversioning): "" "get/something/?version=0.1 http/1.1 host:example . com Accept:application/json "" "Invalid_version_message = _ (' invalid version in query parameter. ') def determine_version (self, request, *args, **kwargs): Version = Request.query_params.get (Self.version_param, self. default_version) if not self.is_allowed_version (version): Raise exceptions. NotFound (Self.invalid_version_message) return version def reverse (self, viewname, Args=none, Kwargs=none, reques T=none, Format=none, **extra): url = Super (queryparameterversioning, self). Reverse (viewname, args, Kwar GS, request, format, **extra) If request.version is not none:return replace_query_param (URL, se Lf.version_param, request.version) return URL
You can see that there are methods in each version-controlled class reverse
, which can be REST framework
used reverse
to reverse the generation of URLs.
Create a new Django project and import it into your project's apprest-framework
settings.py
make the following configuration in the file
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘app01.apps.App01Config‘, ‘rest_framework‘,]REST_FRAMEWORK = { ‘DEFAULT_VERSIONING_CLASS‘: ‘rest_framework.versioning.URLPathVersioning‘, ‘VERSION_PARAM‘: "version", ‘DEFAULT_VERSION‘: ‘V1‘, ‘ALLOWED_VERSIONS‘: [‘v1‘, ‘v2‘]}
Adding routing information to the urls.py file
from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^(?P<version>\w+)/users/$‘,views.UsersView.as_view(),name="test1"),]
views.py
classes defined in a file UserView
from django.shortcuts import render,HttpResponsefrom rest_framework.views import APIViewfrom rest_framework.versioning import URLPathVersioningclass UsersView(APIView): def get(self,request,*args,**kwargs): # 打印版本信息 print("request.version:",request.version) # reverse方法有一个viewname参数,在这里定义为urls.py中定义的name print(request.versioning_scheme.reverse("test1",request=request))
At this point, enter in the browser http://127.0.0.1:8000/v1/users/
, the service side spool information as follows
request.version: v1http://127.0.0.1:8000/v1/users/
And then replace the URL in the browser http://127.0.0.1:8000/v2/users/
, the service end of the print information has become
request.version: v2http://127.0.0.1:8000/v2/users/
You can see that the correct version is printed, and the reverse-build URL is already successful.
Django REST framework Reverse Build URL