首页 > 其他分享 >drf-5个接口

drf-5个接口

时间:2023-05-25 21:12:58浏览次数:57  
标签:ser self request 接口 Book import class drf

目录

写接口前的准备

1 表模型

from django.db import models


class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.CharField(max_length=32)

    publish = models.ForeignKey(to='Publish', on_delete=models.DO_NOTHING, null=True, db_constraint=False)
    authors = models.ManyToManyField(to='Author')


class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)


class Author(models.Model):
    name = models.CharField(max_length=32)
    phone = models.CharField(max_length=11)
    # 本质就是ForeignKey,但是唯一,多的一方唯一,形成了一对一
    author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    email = models.CharField(max_length=32)
    age = models.IntegerField()

序列化类

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

一 继承APIView+序列化类+Resonse写5个接口

视图类

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book
from .serializer import BookSerializer


class BookView(APIView):
    def get(self, request):
        book_list = Book.objects.all()
        ser = BookSerializer(book_list, many=True)
        return Response({'code': 100, 'msg': '查询所有成功', 'data': ser.data})

    def post(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功'})
        else:
            return Response({'code': 100, 'msg': ser.errors})


class BookDetailView(APIView):
    def get(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(book)
        return Response({'code': 101, 'msg': '查询一条成功', 'data': ser.data})

    def put(self, request, pk):
        book = Book.objects.filter(pk=pk).filter()
        ser = BookSerializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def delete(self, request, pk):
        Book.objects.fiter(pk=pk).delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

二 继承GenericAPIView + 序列化类 + Resonse写5个接口

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView


class BookView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(book_list, many=True)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def post(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})


class BookDetailView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def post(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def delete(self, request, pk):
        self.get_object().delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

三 继承GenericAPIView+5个视图扩展类+序列化类+Response写接口

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin


class BookView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)


class BookDetailView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request, pk):
        return self.retrieve(request, pk)

    def put(self, request, pk):
        return self.update(request, pk)

    def delete(self, request, pk):
        return self.destroy(request, pk)

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

四 基于视图子类写5 个接口:9个视图子类--->视图类

单独使用5个类:

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView


class BookView(ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookView(CreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(RetrieveAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(UpdateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(DestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

使用复合的类:

视图类

from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, \
    RetrieveUpdateAPIView


class BookView(ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
]

上面的所有方法中使用的路由都一致,都是原始写法。

五 视图集合

5.1 ModelViewSet

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.viewsets import ModelViewSet


class BookView(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

5.2 ReadOnlyModelViewSet,只有两个方法

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.viewsets import ReadOnlyModelViewSet


class BookView(ReadOnlyModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve'})),
]

# 也可以使用自动生成路由

5.3 ViewSetMixin

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.viewsets import ViewSetMixin
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView


class BookView(ViewSetMixin, ListCreateAPIView, RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

路由

路由可以这么写:

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

5.4 ViewSet

ViewSet =ViewSetMixin+APIView

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet


class BookView(ViewSet):
    def list(self, request):
        book_list = Book.objects.all()
        ser = BookSerializer(book_list, many=True)
        return Response({'code': 100, 'msg': '查询所有成功', 'data': ser.data})

    def create(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功'})
        else:
            return Response({'code': 100, 'msg': ser.errors})

    def retrieve(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(book)
        return Response({'code': 101, 'msg': '查询一条成功', 'data': ser.data})

    def update(self, request, pk):
        book = Book.objects.filter(pk=pk).filter()
        ser = BookSerializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def destroy(self, request, pk):
        Book.objects.fiter(pk=pk).delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

5.5 GenericViewSet

GenericViewSet = ViewSetMixin+GenericAPIView

视图类

from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet


class BookView(GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def list(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(book_list, many=True)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def create(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    # class BookDetailView(GenericAPIView):
    #     queryset = Book.objects.all()
    #     serializer_class = BookSerializer

    def retrieve(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book)
        return Response({'code': 100, 'msg': '成功', 'results': ser.data})

    def update(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '更新成功'})
        else:
            return Response({'code': 101, 'msg': ser.errors})

    def destroy(self, request, pk):
        self.get_object().delete()
        return Response({'code': 100, 'msg': '删除成功'})

路由

urlpatterns = [
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

# 也可以使用自动生成路由

标签:ser,self,request,接口,Book,import,class,drf
From: https://www.cnblogs.com/zjyao/p/17432932.html

相关文章

  • 开发健康状态监控接口
    一、要求接口中需包含逻辑处理和数据库读写,接口的成功真正代表组件运行正常,一旦接口失败真正代表组件运行异常;并将该接口为paas平台的高可用接口,利用该接口设置组件的高可用功能二、实现1)开发一个访问数据库的接口,访问成功,返回状态码200,出现异常,返回状态码5002)为服务调用添加高可用......
  • 淘宝天猫京东1688拼多多商品详情API接口(商品价格监控,商品上传等场景)代码对接
    抓取淘宝商品详情价格接口代码封装如下:请求方式:HTTPS POSTGET公共参数名称类型必须描述key String 是 调用key(必须以GET方式拼接在URL中)API接口 API接口secret String 是 调用密钥api_name String 是 API接口名称(包括在请求地址中)[item_search,item_get,item_search_......
  • 软件接口测试有什么作用?接口测试有哪些好用工具?
    一、软件接口测试有什么作用?在软件开发过程中,接口是不可避免的一部分。接口测试是为了检查软件系统中不同模块之间的接口能否正常工作,以及模块之间的数据是否能够互相传输而进行的测试。接口测试的主要作用包括保证系统区域间的互通性、降低软件的故障率、提高软件的可靠......
  • USB4接口静电浪涌防护,ESD保护二极管选什么型号好?
    与传统的USB一样,USB4接口也是即插即用。与之前的版本USB3.2和Thunderbolt3一样,USB4也要通过使用USBType-C连接器发挥功能。新老电子工程师们都知道,USBType-C接口根据USB3.x和USB4协议传输数据,经常会受到电气过载(EOS)和静电放电(ESD)事件的影响。由于USB4接口体积更加小巧,内部元......
  • 星座运势查询接口
    接入点说明:十二星座为:白羊座、金牛座、双子座、巨蟹座、狮子座、处女座、天秤座、天蝎座、射手座、摩羯座、水瓶座、双鱼座。接口地址:https://route.showapi.com/872-1?showapi_appid=&showapi_sign=  查看密匙返回格式:json  纯java:publicstaticvoidm......
  • 第三方接口控制请求时间处理
    问题项目中需要调用第三方接口,若第三方接口在X秒内未返回,则继续后续业务操作代码展示publicclassCheckTimeOutDemo{privatestaticExecutorServicethreadService=newThreadPoolExecutor(0,20,60L,TimeUnit.SECONDS,newSynchronousQueue<>(),r->{......
  • 基于Qt的音乐播放器(三)通过酷狗音乐的api接口,返回json格式歌曲信息(播放地址,歌词,图片)
    2020博客之星年度总评选进行中:请为74号的狗子投上宝贵的一票!我的投票地址:点击为我投票文章目录前言1.获取歌曲搜索列表api接口2.获取单个歌曲详细信息包括歌词3.总结前言首先说明,本教程仅供个人学习,研究使用,禁止用于任何的商业和非法用途。(手动狗头)之所以要研究这个,是因为我想......
  • Fdog系列(三):使用腾讯云短信接口发送短信,数据库写入,部署到服务器,web收尾篇。
    文章目录1.前言2.使用腾讯云短信接口发送短信3.java连接数据库4.部署到服务器(如果你有的话)目录Fdog系列(一):思来想去,不如写一个聊天软件,那就从仿QQ注册页面开始吧。Fdog系列(二):html写完注册页面之后怎么办,用java写后台响应呀。文章中出现的源码获取方式:评论区留下邮箱地址。创作......
  • 电商erp系统选品,跨境ERP系统选品,api接口采集数据
    ​  电商ERP系统选品优势:1.自动化选品:电商ERP系统可以根据销售数据、客户反馈、市场趋势等因素,自动化地筛选出热销商品,快速进行选品;2.数据分析功能:电商ERP系统可以对历史销售数据进行分析,得出销售趋势、客户偏好等信息,有利于精细化选品;3.库存管理:电商ERP系统可以管理商......
  • 淘宝API接口的各种应用
    淘宝API接口是一种强大且多功能的工具,可帮助开发者利用淘宝平台的海量数据并以此更高效地完成各种任务。不论是想构建一个电商网站,还是想开发一个淘宝购物助手,淘宝API都能帮助你实现这些目标。下文将介绍淘宝API接口的各种特性,帮助开发者全面了解这一工具,更好地利用它。获取商品数......