首页 > python教程

Restful_framework视图组件代码实例解析

时间:2020-11-20 python教程 查看: 917

一、基本视图

写一个出版社的增删查改resful接口

要自己事先创建好django项目,并创建好表,添加完记录

路由:

url(r'^publish/$', views.PublishView.as_view()),
url(r'^publish/(?P\d+)/$', views.PublishDetailView.as_view()),

视图:

from api import modelsfrom rest_framework import serializersfrom rest_framework.response import Responsefrom rest_framework.views import APIView
class PublishSerializers(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'

class PublishView(APIView):
  #查询出版社表中所有记录
  def get(self, request):
    publish_list = models.Publish.objects.all()
    bs = PublishSerializers(publish_list, many=True)
    # 序列化数据

    return Response(bs.data)  #返回的结果是列表中套字典
  
  def post(self, request):
    # 添加一条数据
    print(request.data)

    bs=PublishSerializers(data=request.data)
    if bs.is_valid():
      bs.save() # 生成记录
      return Response(bs.data)  #返回的是添加成功记录的字典
    else:

      return Response(bs.errors)

class PublishDetailView(APIView):   #查询某一条数据
  def get(self,request,pk):
    publish_obj=models.Publish.objects.filter(pk=pk).first()
    bs=PublishSerializers(publish_obj,many=False)
    return Response(bs.data)   #更新某一条数据
  def put(self,request,pk):
    publish_obj = models.Publish.objects.filter(pk=pk).first()

    bs=PublishSerializers(data=request.data,instance=publish_obj)
    if bs.is_valid():
      bs.save() # update
      return Response(bs.data)
    else:
      return Response(bs.errors)   #删除某一条数据
  def delete(self,request,pk):
    models.Publish.objects.filter(pk=pk).delete()

    return Response("")

二、mixins类和generic类编写视图

路由:

url(r'^publishes$', views.Publish.as_view()),
url(r'^publish/(?P\d+)', views.PublishDetail.as_view()),

视图:

from api import models
from rest_framework import serializers
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
class PublishSer(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'
class Publish(GenericAPIView,mixins.ListModelMixin,mixins.CreateModelMixin):
  queryset = models.Publish.objects.all()
  serializer_class = PublishSer
  def get(self,request):
    return self.list(request)  #在ListModelMixin下有一个list方法,返回的就是查询的结果:Response(serializer.data)
  def post(self,request):
    return self.create(request) #已经封装好了,帮我们做校验和序列化,返回的是添加成功的记录
class PublishDetail(GenericAPIView,mixins.DestroyModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin):

  queryset = models.Publish.objects.all()
  serializer_class = PublishSer
  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下ListCreateAPIView和RetrieveUpdateDestroyAPIView

路由:

url(r'^publishes$', views.Publish.as_view()),
url(r'^publish/(?P\d+)', views.PublishDetail.as_view()),

视图:

from api import models
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework import serializers
class Publishser(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'

class Publish(ListCreateAPIView):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser

class PublishDetail(RetrieveUpdateDestroyAPIView):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser

四、使用ModelViewSet

路由:

url(r'^publish$',views.Publish.as_view({'get':'list','post':'create'})),
url(r'^publish/(?P\d+)', views.Publish.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),

视图:

from rest_framework.viewsets import ModelViewSet
from api import models
from rest_framework import serializers
class Publishser(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'
class Publish(ModelViewSet):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

展开全文
上一篇:Manjaro、pip、conda更换国内源的方法
下一篇:详解Pytorch显存动态分配规律探索
输入字:
相关知识
Python 实现图片色彩转换案例

我们在看动漫、影视作品中,当人物在回忆过程中,体现出来的画面一般都是黑白或者褐色的。本文将提供将图片色彩转为黑白或者褐色风格的案例详解,感兴趣的小伙伴可以了解一下。

python初学定义函数

这篇文章主要为大家介绍了python的定义函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助,希望能够给你带来帮助

图文详解Python如何导入自己编写的py文件

有时候自己写了一个py文件,想要把它导入到另一个py文件里面,所以下面这篇文章主要给大家介绍了关于Python如何导入自己编写的py文件的相关资料,需要的朋友可以参考下

python二分法查找实例代码

二分算法是一种效率比较高的查找算法,其输入的是一个有序的元素列表,如果查找元素包含在列表中,二分查找返回其位置,否则返回NONE,下面这篇文章主要给大家介绍了关于python二分法查找的相关资料,需要的朋友可以参考下