Django REST framework基础:视图和路由

Django REST 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来获取。

前戏

葫芦娃的故事

#! /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(r'school/$', views.SchoolView.as_view()),
url(r'school/(?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(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'
})),
复制代码

 

再来一牛之高级路由

视图

同上

路由

from rest_framework.routers import DefaultRouter

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

 

赠图一张,祝君好运

 

 

转载于:https://www.cnblogs.com/PythonMrChu/p/10439982.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值