1. 程式人生 > >Django REST framework反向生成url

Django REST framework反向生成url

turn something ren rest 基於 mine repl djang sage

Django REST framework是一個基於Django的框架,REST framework又是怎麽反向生成url的呢??

在前面的例子中,知道在REST framework中有6種版本控制的方式,進入任意一種版本控制的源碼中,

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, request=None, format=None, **extra):
        url = super(QueryParameterVersioning, self).reverse(
            viewname, args, kwargs, request, format, **extra
        )
        if request.version is not None:
            return replace_query_param(url, self.version_param, request.version)
        return url

可以看到每一個版本控制的類中也都有reverse方法,由此可以了REST framework也是使用reverse的方式來反向生成url

新建一個Django項目,在項目的app中導入rest-framework

settings.py文件中做如下配置

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‘]
}

在urls.py文件中添加路由信息

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^(?P<version>\w+)/users/$‘,views.UsersView.as_view(),name="test1"),
]

views.py文件中定義UserView的類

from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.versioning import URLPathVersioning

class 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))

        return HttpResponse("aaaa") 

此時,在瀏覽器中輸入http://127.0.0.1:8000/v1/users/,在服務端後臺打印信息如下

request.version: v1
http://127.0.0.1:8000/v1/users/

再把瀏覽器中的url更換為http://127.0.0.1:8000/v2/users/,服務端後臺的打印信息又變成了

request.version: v2
http://127.0.0.1:8000/v2/users/

可以看到打印出了正確的版本,並且反向生成url也已經成功了

Django REST framework反向生成url