0


drf之day04: drf请求与响应,drf能够解析的请求编码,响应编码,drf之视图组件,2个视图基类

目录标题

一:drf之请求与响应

1.Request类

1.继承APIView后,请求对象requests每次请求都是一个新的request

2.data: POST, PUT, PATCH请求方式解析后的数据

3.原生django,put提交的数据在request.POST中是娶不到的

4.其他方法用起来和之前是一样的(method, FILES, path)

2.Response类

参数功能data=None把字典,列表序列化成json格式字符串,放到http请求的body中,返回给前端status=Nonehttp响应状态码,默认是200, 201headers=Nonehttp的响应头,是字典格式:{‘name’: ‘zhang’}template_name=None在浏览器中看到好看的页面,指定的模板content_type=None响应编码格式(json)

二.drf能够解析的请求编码,响应编码

1.请求编码
1.默认能解析的请求编码
  • urlencoded,form-data, json
2.如何配置请求编码

其实在drf内置的配置文件中提前就配好了请求编码

drf配置文件settings.py中有DEFAULT_PARSER_CLASSES(默认的解析类)

'rest_framework.parsers.JSONParser', 可以解析json格式
'rest_framework.parsers.FormParser', 可以解析urlencoded格式
'rest_framework.parsers.MultiPartParser' 可以解析form-data格式
方式一:全局配置
REST_FRAMEWORK ={'DEFAULT_PARSER_CLASSES':['rest_framework.parsers.JSONParser',# 'rest_framework.parsers.FormParser',# 'rest_framework.parsers.MultiPartParser',],}
方式二:局部配置
from rest_framework.parsers import JSONParser, FormParser, MultiPartParser

classTestView(APIView):
            parser_classes =[JSONParser,FormParser,MultiPartParser]
2.响应编码

如果用浏览器接收响应,看到的是好看的页面,如果用postman,看到的是json格式

默认情况下,响应的编码是根据客户端类型决定的

方式一:全局配置
    REST_FRAMEWORK ={'DEFAULT_RENDERER_CLASSES':[# 'rest_framework.renderers.JSONRenderer', # json格式'rest_framework.renderers.BrowsableAPIRenderer',#浏览器的格式]}
方式二:局部配置
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer

classTestView(APIView):
    renderer_classes =[JSONRenderer,]

三:drf之视图组件

1.由于drf提供了一个顶层的视图类APIView,以后直接继承APIView写视图类即可

2.后期可以使用面向对象的继承,封装

四:2个视图基类

1.APIView

2.GenericAPIView(继承了APIView)

3.方法:
方法作用self.get_object()根据pk获取单个数据self.get_serializer()获取要使用的序列化类self.get_queryset()获取所有要序列化的数据

作业:

一:继承GenericAPIView,实现5个接口

models.py

classBook(models.Model):
    name = models.CharField(max_length=32)
    price = models.CharField(max_length=32)
    publish = models.CharField(max_length=32)

serializer.py

classBookSerializer(serializers.ModelSerializer):classMeta:
        model = Book
        fields ='__all__'

views.py

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

    defget(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(instance=book_list, many=True)return Response(data=ser.data)defpost(self, request):
        ser = self.get_serializer(data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response(ser.errors)classBookDetailView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    defget(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book)return Response(ser.data)defput(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book, data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response({'code':100,'msg':'修改成功'})defdelete(self, request, pk):
        self.get_queryset().filter(pk=pk).delete()return Response('ok')

urls.py

    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetailView.as_view()),
二:2 使用面向对象,写5个父类, 继承GenericAPIView+某几个父类后,就有某几个接口
  • 方法一:
classCheckOne(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    defget(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book)return Response(ser.data)classCheckAll(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    defget(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(instance=book_list, many=True)return Response(data=ser.data)classAddOne(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    defpost(self, request):
        ser = self.get_serializer(data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response(ser.errors)classChangeOne(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    defput(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book, data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response({'code':100,'msg':'修改成功'})classDeleteOne(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    defdelete(self, request, pk):
        self.get_queryset().filter(pk=pk).delete()return Response('ok')classBookView(CheckAll, AddOne):def__init__(self):super(CheckAll, self).__init__()super(AddOne, self).__init__()classBookDetailView(CheckOne, ChangeOne, DeleteOne):def__init__(self):super(CheckOne, self).__init__()super(ChangeOne, self).__init__()super(DeleteOne, self).__init__()
  • 方法二:
classCheckOne:defget(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book)return Response(ser.data)classCheckAll:defget(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(instance=book_list, many=True)return Response(data=ser.data)classAddOne:defpost(self, request):
        ser = self.get_serializer(data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response(ser.errors)classChangeOne:defput(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book, data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response({'code':100,'msg':'修改成功'})classDeleteOne:defdelete(self, request, pk):
        self.get_queryset().filter(pk=pk).delete()return Response('ok')classBookView(GenericAPIView, CheckAll, AddOne):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    def__init__(self):super(CheckAll, self).__init__()super(AddOne, self).__init__()classBookDetailView(GenericAPIView, CheckOne, ChangeOne, DeleteOne):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    def__init__(self):super(CheckOne, self).__init__()super(ChangeOne, self).__init__()super(DeleteOne, self).__init__()
三:写9个视图子类
# Create your views here.# 1:查看一条数据classCheckOne:defget(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book)return Response(ser.data)# 2:查看所有数据classCheckAll:defget(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(instance=book_list, many=True)return Response(data=ser.data)# 3.增加一条数据classAddOne:defpost(self, request):
        ser = self.get_serializer(data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response(ser.errors)# 4:修改一条数据classChangeOne:defput(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book, data=request.data)if ser.is_valid():
            ser.save()return Response(ser.data)else:return Response({'code':100,'msg':'修改成功'})# 5:删除一条数据classDeleteOne:defdelete(self, request, pk):
        self.get_queryset().filter(pk=pk).delete()return Response('ok')# 6:查看所有+增加一条classGetAllandPost(CheckAll, AddOne):def__init__(self):super(CheckAll, self).__init__()super(AddOne, self).__init__()# 7:查看一条+修改一条classGetOneandPut(CheckOne, ChangeOne):def__init__(self):super(CheckOne, self).__init__()super(ChangeOne, self).__init__()# 8:查看一条+删除一条classGetOneandDelete(CheckOne, DeleteOne):def__init__(self):super(CheckOne, self).__init__()super(DeleteOne, self).__init__()# 9:删除一条+修改一条classDeleteandPut(DeleteOne, ChangeOne):def__init__(self):super(DeleteOne, self).__init__()super(DeleteOne, self).__init__()# class BookView(GenericAPIView, CheckAll, AddOne):#     queryset = Book.objects.all()#     serializer_class = BookSerializer#     def __init__(self):#         super(CheckAll, self).__init__()#         super(AddOne, self).__init__()# class BookDetailView(GenericAPIView, CheckOne, ChangeOne, DeleteOne):#     queryset = Book.objects.all()#     serializer_class = BookSerializer#     def __init__(self):#         super(CheckOne, self).__init__()#         super(ChangeOne, self).__init__()#         super(DeleteOne, self).__init__()classBookDetailView(GenericAPIView,GetOneandPut):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    def__init__(self):super(CheckOne, self).__init__()super(ChangeOne, self).__init__()classBookView(GenericAPIView, GetAllandPost):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    def__init__(self):super(GetAllandPost, self).__init__()
标签: postman 测试工具

本文转载自: https://blog.csdn.net/Yydsaoligei/article/details/127112378
版权归原作者 Jayxieming 所有, 如有侵权,请联系我们删除。

“drf之day04: drf请求与响应,drf能够解析的请求编码,响应编码,drf之视图组件,2个视图基类”的评论:

还没有评论