drf--视图,路由

Posted qiaodongdong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了drf--视图,路由相关的知识,希望对你有一定的参考价值。

DRF中的Request

在Django REST Framework中内置的Request类扩展了Django中的Request类,实现了很多方便的功能--如请求数据解析和认证等。

比如,区别于Django中的request从request.GET中获取URL参数,从request.POST中取某些情况下的POST数据。

在APIView中封装的request,就实现了请求数据的解析:

对于GET请求的参数我们通过request.query_params来获取。

对于POST请求、PUT请求的数据我们通过request.data来获取。

前戏

葫芦娃的故事

技术分享图片
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2018/8/1


class Wa1(object):
    name = "红娃"

    def f1(self):
        print("力大无穷!")


class Wa2(object):
    name = 橙娃

    def f2(self):
        print(千里眼顺风耳!)


class Wa3(object):
    name = 黄娃

    def f3(self):
        print(钢筋铁骨!)


class Wa4(object):
    name = 绿娃

    def f4(self):
        print("会喷火!")


class Wa5(object):
    name = 青蛙

    def f5(self):
        print("会喷水!")


class Jishuwa(Wa1, Wa3, Wa5):
    name = 奇数娃

    def ff(self):
        print("我是{}, 我会:".format(self.name))
        self.f1()
        self.f3()
        self.f5()


class Oushuwa(Wa2, Wa4):
    name = 偶数娃

    def ff(self):
        print("我是{}, 我会:".format(self.name))
        self.f2()
        self.f4()


dbg = Jishuwa()
dbg.ff()
zhq = Oushuwa()
zhq.ff()


# 直接定义一个基数娃
class Taowa(Wa1, Wa3, Wa5):
    name = 套娃

    def ff(self):
        print("我是{}, 我会:".format(self.name))
        self.f1()
        self.f3()
        self.f5()


class Wawa(Taowa):
    pass


print("=" * 120)
a = Wawa()
a.ff()
View Code

 

前提

序列化

技术分享图片
from rest_framework import serializers
from app01 import models


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        fields = "__all__"
        extra_kwargs = {
            "content": {"error_messages": {"required": "评论内容不能为空"}},
            "article": {"error_messages": {"required": "文章不能为空"}}
        }


class SchoolSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.School
        fields = "__all__"
技术分享图片

 

初生牛犊之徒手垒代码阶段

视图

技术分享图片
class SchoolView(APIView):
    def get(self, request, *args, **kwargs):
        query_set = models.School.objects.all()
        ser_obj = app01_serializers.SchoolSerializer(query_set, many=True)
        return Response(ser_obj.data)


class SchoolDetail(APIView):
    def get(self, request, pk, *args, **kwargs):
        obj = models.School.objects.filter(pk=pk).first()
        ser_obj = app01_serializers.SchoolSerializer(obj)
        return Response(ser_obj.data)
技术分享图片

 

小试牛刀之使用混合类阶段

视图

技术分享图片
class SchoolView(GenericAPIView, mixins.ListModelMixin):
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


class SchoolDetail(GenericAPIView, mixins.RetrieveModelMixin, mixins.CreateModelMixin):
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer

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

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
技术分享图片

路由

url(rschool/$, views.SchoolView.as_view()),
url(rschool/(?P<pk>d+)/$, views.SchoolDetail.as_view()),

 

牛气冲天之使用通用类

视图

技术分享图片
class SchoolView(ListCreateAPIView):
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer


class SchoolDetail(RetrieveUpdateDestroyAPIView):
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer
技术分享图片

路由

同上

牛牛牛牛之使用视图集

视图

class SchoolView(ModelViewSet):
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer

路由

技术分享图片
url(rschool/$, views.SchoolView.as_view({
    "get": "list",
    "post": "create",
})),
url(rschool/(?P<pk>d+)/$, views.SchoolView.as_view({
    get: retrieve,
    put: update,
    patch: partial_update,
    delete: destroy
})),
技术分享图片

 

再来一牛之高级路由

视图

同上

路由

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(rschool, views.SchoolView)
urlpatterns += router.urls

 

赠图一张,祝君好运

 

技术分享图片

 

以上是关于drf--视图,路由的主要内容,如果未能解决你的问题,请参考以下文章

DRF之路由系统与视图

DRF视图家族

77-drf视图家族及路由层补充

drf之视图类与路由

DRF视图和路由

drf-视图集路由系统action装饰器