码迷,mamicode.com
首页 > 其他好文 > 详细

rest-framework框架的基本组件

时间:2019-07-20 23:02:30      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:pattern   request   you   blank   char   form   代码片段   kde   cut   

rest-framework框架

rest-framework是django基于restful协议提供的用于前后端分离的框架,核心思想是一切皆是资源,操作只是请求方式。注意:最后后端只会向前端返回json数据。

如数据库模型表book

    url           请求方式       视图
    book/          get          books
    book/          post         books
    book/(\d+)/    get          book_detail 
   book
/(\d+)/ put book_detail book/(\d+)/ delete book_detail class Books(View): def get(self,request): pass # 查询所有书籍 def post(self,request): pass # 添加书籍 class BookDetail(View): def get(self,request,id): pass # 查询某本书籍 def put(self,request,id): pass # 更新某本书籍 def delete(self,request,id): pass # 删除某本书籍

 

 

快速实例

Quickstart

序列化

创建一个序列化类

开发我们的Web API的第一件事是为我们的Web API提供一种将代码片段实例序列化和反序列化为诸如json之类的表示形式的方式。我们可以通过声明与Django forms非常相似的序列化器(serializers)来实现。

models部分:

from django.db import models

# Create your models here.


class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.IntegerField()
    pub_date = models.DateField()
    publish = models.ForeignKey("Publish")
    authors = models.ManyToManyField("Author")

    def __str__(self):
        return self.title


class Publish(models.Model):
    name = models.CharField(max_length=32)
    email = models.EmailField()

    def __str__(self):
        return self.name


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()

    def __str__(self):
        return self.name

 

 

views部分:

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from django.shortcuts import HttpResponse
from django.core import serializers


from rest_framework import serializers

class BookSerializers(serializers.Serializer):
    title=serializers.CharField(max_length=32)
    price=serializers.IntegerField()
    pub_date=serializers.DateField()
    publish=serializers.CharField(source="publish.name")
    #authors=serializers.CharField(source="authors.all")
    authors=serializers.SerializerMethodField()
    def get_authors(self,obj):
        temp=[]
        for author in obj.authors.all():
            temp.append(author.name)
        return temp


class BookViewSet(APIView):

    def get(self,request,*args,**kwargs):
        book_list=Book.objects.all()
        # 序列化方式1:
        # from django.forms.models import model_to_dict
        # import json
        # data=[]
        # for obj in book_list:
        #     data.append(model_to_dict(obj))
        # print(data)
        # return HttpResponse("ok")

        # 序列化方式2:
        # data=serializers.serialize("json",book_list)
        # return HttpResponse(data)

        # 序列化方式3:
        bs=BookSerializers(book_list,many=True)
        return Response(bs.data)

 

 

ModelSerializer

class BookSerializers(serializers.ModelSerializer):
      class Meta:
          model=Book
          fields="__all__"
          depth=1
    # # 一对多
    # publish = serializers.CharField(source="publish.name")
    # # 多对多
    # authors = serializers.SerializerMethodField()
    #
    # def get_authors(self, obj):
    #     temp = []
    #     for author in obj.authors.all():
    #         temp.append(author.name)
    #     return temp

 

提交post请求

def post(self,request,*args,**kwargs):
       
        bs=BookSerializers(data=request.data,many=False)
        if bs.is_valid():
            # print(bs.validated_data)
            bs.save()
            return Response(bs.data)
        else:
            return HttpResponse(bs.errors)

 

重写save中的create方法

class BookSerializers(serializers.ModelSerializer):

      class Meta:
          model=Book
          fields="__all__"
          # exclude = [‘authors‘,]
          # depth=1

      def create(self, validated_data):
          authors = validated_data.pop(authors)
          obj = Book.objects.create(**validated_data)
          obj.authors.add(**authors)
          return obj

 

 

单条数据的get和put请求

class BookDetailViewSet(APIView):

    def get(self,request,pk):
        book_obj=Book.objects.filter(pk=pk).first()
        bs=BookSerializers(book_obj)
        return Response(bs.data)

    def put(self,request,pk):
        book_obj=Book.objects.filter(pk=pk).first()
        bs=BookSerializers(book_obj,data=request.data)
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return HttpResponse(bs.errors)

 超链接API:Hyperlinked

from rest_framework import serializers
from app01 import models

# publish模型表序列化
class PublishModelSer(serializers.ModelSerializer):
    class Meta:
        model = models.Publish
        fields = "__all__"
# book模型表序列化
class BookSerializers(serializers.ModelSerializer):
      publish= serializers.HyperlinkedIdentityField(
                     view_name=publish_detail,
                     lookup_field="publish_id",
                     lookup_url_kwarg="pk")
      class Meta:
          model=Book
          fields="__all__"
          #depth=1

# 书籍信息
class BooksView(APIView):
    # 查询所有书籍
    def get(self, request):
        book_list = models.Book.objects.all()
        # 将queryset转化为序列化的数据
        bs = BookModelSerializers(book_list, many=True,context={request: request})
        return Response(bs.data)

    # 添加书籍
    def post(self, request):
        bs = BookModelSerializers(data=request.data,many=False)
        if bs.is_valid():
            bs.save()  # 执行create方法
            print("bs.validated_data:", bs.validated_data)
            return Response(bs.data)
        else:
            return Response(bs.errors)        



# 出版社单条数据
class PublishDetailView(APIView):
    # 查看某个出版社信息
    def get(self,request,pk):
        publish = models.Publish.objects.filter(pk=pk).first()
        ps = PublishModelSer(publish)
        return Response(ps.data)

    # 更新某个出版社信息
    def put(self,request,pk):
        publish = models.Publish.objects.filter(pk=pk).first()
        ps = PublishModelSer(publish,data=request.data)
        if ps.is_valid():
            ps.save()
            return Response(ps.data)
        else:
            return Response(ps.errors)

    # 删除某个出版社信息
    def delete(self,request,pk):
        models.Publish.objects.filter(pk=pk).delete()
        return Response()

 

注意:url部分

urlpatterns = [

    url(r^publishes/$, views.Publish.as_view(), name="publish"),
    url(r^publishes/(?P<pk>\d+)/$, views.PublishDetailView.as_view(), name="publish_detail"),

    url(r^books/$, views.BooksView.as_view(), name="book"),
    url(r^books/(\d+)/$, views.BookDetailView.as_view(), name="book_detail")
]

 

 

视图三部曲

 

rest-framework框架的基本组件

标签:pattern   request   you   blank   char   form   代码片段   kde   cut   

原文地址:https://www.cnblogs.com/yunwangjun-python-520/p/11219526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!