码迷,mamicode.com
首页 > 其他好文 > 详细

django-rest-framework学习之Class-based Views--2017年4月13日

时间:2017-04-13 19:08:41      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:bad   http404   frame   通用   使用   errors   ons   pos   代码   

Class-based Views
减少代码重复
提高代码重用
 
【1】用Class-based Views重写API
from myLesson.models import MyLesson
from myLesson.serializers import MyLessonSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
 
class MyLessonList(APIView):
    """
    List all myLesson, or create a new myLesson.
    """
    def get(self,request,format=None):
        myLesson = MyLesson.objects.all()
        serializer = MyLessonSerializer(myLesson,many=True)
        return Response(serializer.data)
 
    def post(self,reuqest,format=None):
        serializer = Myserializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer.errors,stauts=status.HTTP_400_BAD_REQUEST)
 
class MyLessonDetail(APIView):
    """
    Retrieve,update or delete a myLesson instance.
    """
    def get_object(self,pk):
        try:
            return MyLesson.objects.get(pk=pk)
        except MyLesson.DoesNotExist:
            raise Http404
 
    def get(self,request,pk,format=None):
        myLesson = self.get_object(pk)
        serializer = MyLessonSerializer(myLesson)
        return Response(serializer.data)
 
    def put(self,request,pk,format=None):
        myLesson = self.get_object(pk)
        serializer = MyLessonSerializer(myLesson,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
 
    def delete(self,request,pk,format=None):
        myLesson = self.get_object(pk)
        myLesson.delete()
        return Response(status.HTTP_204_NO_CONTENT)
 
 
 
from django.conf.urls import url
from myLesson import views
from rest_framework.urlpatterns import format_suffix_patterns
 
urlpatterns = [
    url(r^myLesson/$,views.MyLessonList.as_view()),
    url(r^myLesson/(?P<pk>[0-9]+)/$,views.MyLessonDetail.as_view()),
]
 
urlpatterns = format_suffix_patterns(urlpatterns)

 

 
【2】 mixins
minxin类实现了通用的http的各种方法
使用 GenericAPIView 创建了我们的视图,并且加入了 ListModelMixin 和 CreateModelMixin 。
基本类提供了核心的功能,而混入(mixin)类提供了 .list() 和 .create() 行为。然后,我们显式地在 get 和 post 方法里面,放入对应的行动。
 
from myLesson.models import MyLesson
from myLesson.serializers import MyLessonSerializer
from rest_framework import mixins
from rest_framework import generics
 
class MyLessonList(mixins.ListModelMixin,
                   mixins.CreateModelMixin,
                   generics.GenericAPIView):
    queryset = MyLesson.objects.all()
    serializer_class = MyLessonSerializer
 
    def get(self,request,*args,**kwargs):
        return self.list(request,*args,**kwargs)
 
    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)
 
class MyLessonDetail(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.DestroyModelMixin,
                     generics.GenericAPIView):
    queryset = MyLesson.objects.all()
    serializer_class = MyLessonSerializer
 
    def get(self,request,*args,**kwargs):
        return self.retrieve(request,*args,**kwargs)
 
    def put(self,request,*args,**kwargs):
        return self.update(request,*args,**kwargs)
 
    def delete(self,request,*args,**kwargs):
        return self.destroy(request,*args,**kwargs)
 
 
使用基于泛类(generic class)的视图:
REST framework提供了一套已经实现了混入类的通用视图
from myLesson.models import MyLesson
from myLesson.serializers import MyLessonSerializer
from rest_framework import generics

class MyLessonList(generics.ListCreateAPIView):
    queryset = MyLesson.objects.all()
    serializer_class = MyLessonSerializer

class MyLessonDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = MyLesson.objects.all()
    serializer_class = MyLessonSerializer

 

django-rest-framework学习之Class-based Views--2017年4月13日

标签:bad   http404   frame   通用   使用   errors   ons   pos   代码   

原文地址:http://www.cnblogs.com/jingbostar/p/6705496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!