Django REST Framework基础:视图和路由

举报
Yuchuan 发表于 2020/12/26 13:20:29 2020/12/26
【摘要】 Framework基础:视图和路由学习

一、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来获取。

二、前戏

1、葫芦娃的故事

#! /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()

三、前提

1、序列化

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__"

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

1、视图

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)

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

1、视图

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)

2、路由

url(r'school/$', views.SchoolView.as_view()),
url(r'school/(?P<pk>\d+)/$', views.SchoolDetail.as_view()),

六、牛气冲天之使用通用类

1、视图

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

2、路由

同上

七、牛牛牛牛之使用视图集

1、视图

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

2、路由

url(r'school/$', views.SchoolView.as_view({
    "get": "list",
    "post": "create",
})),
url(r'school/(?P<pk>\d+)/$', views.SchoolView.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})),

八、再来一牛之高级路由

1、视图

同上

2、路由

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'school', views.SchoolView)
urlpatterns += router.urls

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。