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