DRF--view

简介: DRF--view

在学django的时候,我们写视图是这样的

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@csrf_exempt  # 这个函数可以跨域访问
def snippet_list(request):
    if request.method == 'GET':  # get请求
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)  # 序列化
        return JsonResponse(serializer.data, safe=False)
    if request.method == 'POST':  # post请求
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)  # 序列化
        if serializer.is_valid():  # 验证序列化
            serializer.save()  # 保持数据
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def snippet_detail(request, pk):  # 获取单个数据
    try:
        snippet = Snippet.objects.get(pk=pk)  # ORM的模型的对象,一个
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)
    if request.method == 'GET':  # 获取单个数据
        serializer = SnippetSerializer(snippet)
        return JsonResponse(serializer.data)
    if request.method == 'PUT':  # 修改单个数据
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)
    if request.method == 'DELETE':  # 删除单个数据
        snippet.delete()
        return HttpResponse(status=204)

第二版

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@api_view(['GET', "POST"])  # get和post可以访问
def snippet_list(request, format=None):
    if request.method == 'GET':  # get对应的方法,获取全部数据
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)
    if request.method == 'POST':  # post对应的方法
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():  # validated_data
            serializer.save()  # ORM,保存到数据库中
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])  # 获取单个数据,put,delete对应的方法
def snippet_detail(request, pk, format=None):
    try:
        snippet = Snippet.objects.get(pk=pk)  # ORM的模型的对象,一个
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':  # 获取单条数据
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)
    if request.method == 'PUT':  # 修改数据
        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)
    if request.method == 'DELETE':  # 删除数据
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

第三版,使用APIView

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):  # 继承APIView
    def get(self, request, format=None):  # get请求获取所有数据
        snippets = Snippet.objects.all()  # 查询数据
        serializer = SnippetSerializer(snippets, many=True)  # 序列化
        return Response(serializer.data)
    def post(self, request, format=None):  # post请求
        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):
    def get_object(self, pk):
        try:
            snippet = Snippet.objects.get(pk=pk)  # ORM的模型的对象,一个
            return snippet
        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)

第四版,混入mixin

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import mixins  # 导入mixins
from rest_framework import generics  # 导入generics
# ListModelMixin获取所有数据,CreateModelMixin创建数据
class SnippetList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = Snippet.objects.all()  # filter()
    serializer_class = SnippetSerializer  # 序列化对象
    def get(self, request, *args, **kwargs):
        # 调用ListModelMixin下的list方法,获取所有数据
        return self.list(request, *args, **kwargs)
    def post(self, request, *args, **kwargs):
        # 调用CreateModelMixin下的create方法,添加数据
        return self.create(request, *args, **kwargs)
# RetrieveModelMixin获取单条数据,UpdateModelMixin修改数据,DestroyModelMixin删除数据
class SnippetDetail(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
    queryset = Snippet.objects.all()  # filter()
    serializer_class = SnippetSerializer
    def get(self, request, *args, **kwargs):
        # 调用RetrieveModelMixin下的retrieve方法,获取单条数据
        return self.retrieve(request, *args, **kwargs)
    def put(self, request, *args, **kwargs):
        # 调用UpdateModelMixin下的update方法,修改数据
        return self.update(request, *args, **kwargs)
    def delete(self, request, *args, **kwargs):
        # 调用DestroyModelMixin下的destroy方法,删除数据
        return self.destroy(request, *args, **kwargs)

第五版,上面的在简化

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from rest_framework import permissions
from snippets.permissions import IsOwnerOrReadOnly
# generics.ListCreateAPIView继承了mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView
# 获取所有数据(List),添加数据(Create)
class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
# generics.RetrieveUpdateDestroyAPIView继承了mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin
# 获取单个数据(Retrieve),修改数据(Update),删除数据(Destroy)
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    # 当获取单个数据,修改数据,删除数据的时候,就去父类RetrieveUpdateDestroyAPIView找
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

相关文章
|
7月前
|
前端开发 Swift iOS开发
在SwiftUI中,视图(Views)
在SwiftUI中,视图Views
79 2
|
7月前
|
监控 数据可视化 Linux
Qt Model&View&Delegate(模型-视图-代理) 介绍和使用
Qt Model&View&Delegate(模型-视图-代理) 介绍和使用
Qt Model&View&Delegate(模型-视图-代理) 介绍和使用
|
前端开发 安全 API
DRF--介绍和安装
DRF--介绍和安装
|
XML 前端开发 Java
SpringMVC常见组件之View分析
SpringMVC常见组件之View分析
101 0
|
前端开发 数据库 数据安全/隐私保护
Django-View视图
Django-View视图
68 0
|
容器 数据安全/隐私保护 JavaScript
View组件
一、使用方法 view组件是最常用的,也是最简单的视图容器。它是一个块级容器组件,它没有特殊的功能,主要用于布局展示,是布局中最基本的UI组件。几乎所有复杂的布局都可以通过嵌套view来实现。 view除了公共属性之外,还有以下几个私有属性 属性名 类型 默认值 说明hover-.
3047 0
|
XML 数据格式 容器
View-Layout注入框架--简洁视图注入
框架开发前 在没有这套框架之前,我们在activity、fragment、自定义view、listview的viewholder甚至你能想的更多。 大概是这样: //activity protected void onCreate(Bundle savedInstanceState) { super.
967 0

热门文章

最新文章