Django REST framework基礎:視圖和路由

Django REST framework基礎:視圖和路由

 

DRF中的Request

在Django REST Framework中內置的Request類擴展了Django中的Request類,實現了不少方便的功能--如請求數據解析和認證等。html

好比,區別於Django中的request從request.GET中獲取URL參數,從request.POST中取某些狀況下的POST數據。python

在APIView中封裝的request,就實現了請求數據的解析:app

對於GET請求的參數咱們經過request.query_params來獲取。ide

對於POST請求、PUT請求的數據咱們經過request.data來獲取。post

前戲

葫蘆娃的故事

#! /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
複製代碼

路由

同上ui

牛牛牛牛之使用視圖集

視圖

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'
})),
複製代碼

 

再來一牛之高級路由

視圖

同上this

路由

from rest_framework.routers import DefaultRouter

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

 

贈圖一張,祝君好運

 

相關文章
相關標籤/搜索