1. 程式人生 > >Django-Rest frameworw之路由系統

Django-Rest frameworw之路由系統

路由系統

============******============

                        一、 自定義路由

                        二、 半自動路由

                        三、 全自動路由

============******============

路由系統包含的類:

class ViewSetMixin(object): # 重寫as_view方法 支援as_view({'get':'get','post':'add'})
	pass

class ViewSet(ViewSetMixin, views.APIView): # 
	pass  

class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
	pass

class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet): #對資料進行操作
    pass 

路由系統示例展示

一、 自定義路由

in 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())
	]

in 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('...')

二、 半自動路由

in 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'})),
	]
in 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

三、 全自動路由

in urls.py
	from django.conf.urls import url, include
	from rest_framework import routers
	from web.views import s10_generic

	router = routers.DefaultRouter()
	router.register(r'users', s10_generic.UserViewSet)

	urlpatterns = [
	    url(r'^', include(router.urls)),
	]
in 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 UserViewSet(ModelViewSet):
	    queryset = models.UserInfo.objects.all()
	    serializer_class = UserSerializer