django-rest-framework笔记-类视图篇

snippet/url.py

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = [
    url(r‘^snippets/$‘, views.SnippetList.as_view()),
    url(r‘^snippets/(?P<pk>[0-9]+)/$‘, views.SnippetDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

一、使用基本类视图API

snippet/views.py

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class SnippetList(APIView):
    """
    List all snippets, or create a new snippet.
    """
    def get(self, request, format=None):
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class SnippetDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet, 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):
        snippet = self.get_object(pk)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

s
二、使用Mixins

snippet/views.py

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import mixins
from rest_framework import generics

class SnippetList(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

    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 SnippetDetail(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

    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)

三、使用generator基础视图类

snippet/views.py

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
时间: 2024-12-29 15:54:12

django-rest-framework笔记-类视图篇的相关文章

Django REST framework(基于类的视图CBV)

一丶基于类的视图 views.py下 from snippets.models import Snippet from snippets.serializers import SnippetSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import

django framework插件类视图方法

1.使用类视图APIView重写API 类视图APIView,取代@api_view装饰器,代码如下: from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from snippets.models import Snippet from snippets.serializers import SnippetSe

Django Restful Framework【第三篇】认证、权限、限制访问频率

一.认证 认证请求头 views.py #!/usr/bin/env python # -*- coding:utf-8 -*- from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import BaseAuthentication from rest_framework.permissions import

django rest_framework入门四-类视图APIView

上节,我们使用函数视图,用了@api_view装饰器来修饰,这一节,我们介绍类视图APIView,显然,类视图更符合面向对象的原则. 1.使用类视图APIView重写API 类视图APIView,取代@api_view装饰器,代码如下: from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from snippe

Django Restful Framework【第五篇】分页、视图、路由、渲染器

一.分页 试问如果当数据量特别大的时候,你是怎么解决分页的? 方式a.记录当前访问页数的数据id 方式b.最多显示120页等 方式c.只显示上一页,下一页,不让选择页码,对页码进行加密 1.基于limit offset 做分页 from rest_framework.pagination import LimitOffsetPagination urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^app01/(?P<v

Django Restful Framework【第四篇】版本、解析器、序列化和请求数据验证

一.版本 程序也来越大时,可能通过版本不同做不同的处理 没用rest_framework之前,我们可以通过以下这样的方式去获取. class UserView(APIView): def get(self,request,*args,**kwargs): version = request.query_params.get('version') print(version) if version=='v1': #如果版本是v1 ret = { 'code':111, 'msg':'版本一的内容'

django book学习笔记——高级视图和URL配置

1.URLconf技巧 1).流线型化函数导入 在 URLconf 中的每一个入口包括了它所联系的视图函数,直接传入了一个函数对象. 这就意味着需要在模块开始处导入视图函数.但随着 Django 应用变得复杂,它的 URLconf 也在增长,并且维护这些导入可能使得管理变麻烦. 为了避免这种麻烦,Django 提供了一种方法可以在 URLconf 中为某个特别的模式指定视图函数: 你可以传入一个包含模块名和函数名的字符串,而不是函数对象本身.例如: from django.conf.urls.d

Django REST framework基础:视图和路由

在原来modelserializers基础上进行了一次封装方便了使用 # author class AuthorModelSerializers(serializers.ModelSerializer): class Meta: model = models.Author fields = "__all__" from rest_framework import mixins from rest_framework import generics class AuthorView(mi

第三模块-第一章笔记(类实例化篇)

定义类与实例化 #定义父类 用于单位转换 class ScaleConverter: def __init__(self,unit_from,unit_to,factor): #第一个参数必须是self self.unit_from=unit_from self.unit_to=unit_to self.factor=factor def description(self): #函数必须传入self,self用于区分是哪个对象调用该方法 return 'Convert '+self.unit_f