rest framework 之路由系统

Posted midworld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rest framework 之路由系统相关的知识,希望对你有一定的参考价值。

一、自定义路由

1、urls.py

from django.conf.urls import url, include
from web.views import s11_render

urlpatterns = [
    url(r'^test/$', s11_render.TestView.as_view()),
    url(r'^test\.(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view()),
    url(r'^test/(?P<pk>[^/.]+)/$', s11_render.TestView.as_view()),
    url(r'^test/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view())
]

2、views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from .. import models


class TestView(APIView):
    def get(self, request, *args, **kwargs):
        print(kwargs)
        print(self.renderer_classes)
        return Response('...')

二、半自动路由

1、urls.py

from django.conf.urls import url, include
from web.views import s10_generic

urlpatterns = [
    url(r'^test/$', s10_generic.UserViewSet.as_view('get': 'list', 'post': 'create')),
    url(r'^test/(?P<pk>\d+)/$', s10_generic.UserViewSet.as_view(
        'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy')),
]

2、views.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from .. import models


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"


class UserViewSet(ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = UserSerializer

三、全自动路由

1、urls.py

from django.conf.urls import url, include
from rest_framework import routers
from api.views import TestView, TestView1


router = routers.DefaultRouter()
router.register(r'test1', TestView1)

urlpatterns = [
    url(r'^(?P<version>[v1|v2]+)/', include(router.urls)),
]

2、views.py

from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from .. import models


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"

class TestView1(ModelViewSet):
    queryset = models.Role.objects.all()
    serializer_class = TestSerializers
    pagination_class = PageNumberPagination

以上是关于rest framework 之路由系统的主要内容,如果未能解决你的问题,请参考以下文章

rest-framework之url控制

Django rest-framework框架-组件之路由

REST framework (组件使用之认证权限访问频率)

Django REST framework框架之GET, POST, PUT, PATCH, DELETE等API请求接口设计

(了解)rest_framework之版本控制, 响应器, url控制器

rest_framework:url控制