标签:www. indent text api web api index tps cas size
Rest-framework框架的基本组件
json
之类的表示形式的方式。我们可以通过声明与Django forms非常相似的序列化器(serializers)来实现。from django.db import models
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.IntegerField()
pub_date = models.DateField()
publish = models.ForeignKey("Publish", on_delete=models.CASCADE)
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
...
path(‘publishes/‘, views.PublishesView.as_view()),
...
import json
from django.shortcuts import render, HttpResponse
from django.views import View
from django.forms.models import model_to_dict
from .models import *
class PublishesView(View):
# Publish.objects.all().values("name", "email")
# <QuerySet [{‘name‘: ‘苹果出版社‘, ‘email‘: ‘123@qq.com‘}, {‘name‘: ‘橘子出版社‘, ‘email‘: ‘234@qq.com‘}]>
# list(Publish.objects.all().values("name", "email"))
# [{‘name‘: ‘苹果出版社‘, ‘email‘: ‘123@qq.com‘}, {‘name‘: ‘橘子出版社‘, ‘email‘: ‘234@qq.com‘}]
def get(self, request):
# 序列化方式一
# publish_list = list(Publish.objects.all().values("name", "email")) # 注意这个list()
# return HttpResponse(json.dumps(publish_list))
# 序列化方式二
# 使用model_to_dict(obj)
# publish_list = Publish.objects.all()
# temp = []
# for obj in publish_list: # 每一个obj就是类对象
"""
temp.append({
"name": "obj.name",
"email": "obj.email"
})
"""
# temp.append(model_to_dict(obj))
# return HttpResponse(json.dumps(temp))
# 序列化方式三
# publish_list = Publish.objects.all()
# from django.core import serializers
# ret = serializers.serialize(‘json‘, publish_list)
# return HttpResponse(ret)
采用restframework
def post(self, request):
pass
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView
# 为queryset做序列化
class PublishSerializers(serializers.Serializer):
"""等同于form.Form"""
name = serializers.CharField()
email = serializers.CharField()
class PublishesView(APIView):
def get(self, request):
publish_list = Publish.objects.all()
ps = PublishSerializers(publish_list, many=True) # 即可接收Queryset 也可接收 model_obj
return Response(ps.data)
def post(self, request):
pass
[
{
"name": "苹果出版社",
"email": "123@qq.com"
},
{
"name": "橘子出版社",
"email": "234@qq.com"
}
]
class PublishesView(View):
def post(self, request):
print("POST", request.POST)
print("BODY", request.body)
return HttpResponse("POST")
>>>POST <QueryDict: {‘a‘: [‘1‘], ‘b‘: [‘2‘]}>
[18/Oct/2018 16:19:02] "POST /publishes/ HTTP/1.1" 200 4
BODY b‘a=1&b=2‘
# request 源码的入口
from django.core.handlers.wsgi import WSGIRequest
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.views import APIView
class PublishesView(APIView):
def post(self, request):
# 原生的request支持的操作
# print("POST", request.POST)
# print("BODY", request.body)
return Response("POST")
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView
# 为queryset做序列化
class BookSerializers(serializers.Serializer):
"""Book表是一个比较复杂的表包含了一对多与多对多"""
title = serializers.CharField()
price = serializers.IntegerField()
pub_date = serializers.DateField()
# 这怎么办?
# publish = models.ForeignKey("Publish", on_delete=models.CASCADE) # 一对多
# authors = models.ManyToManyField("Author") # 多对多
publish = serializers.CharField(source="publish.name") # 一对多、类名小写
# 多对多的话这个sourse不好使,得到的是Queryset
authors = serializers.CharField(source="authors.all") # 多对多、类名小写.all() 自动执行
class BookView(APIView):
def get(self, request):
book_list = Book.objects.all()
bs = BookSerializers(book_list, many=True)
return Response(bs.data)
def post(self, request):
pass
[
{
"title": "你好,再见",
"price": 99,
"pub_date": null,
"publish": "苹果出版社",
"authors": "<QuerySet [<Author: pontoon>, <Author: toonpon>]>" # 得到一个QuerySet
},
{
"title": "再见,你好",
"price": 88,
"pub_date": null,
"publish": "橘子出版社",
"authors": "<QuerySet [<Author: pontoon>]>"
},
{
"title": "谁动了我的奶酪?",
"price": 77,
"pub_date": null,
"publish": "苹果出版社",
"authors": "<QuerySet []>"
}
]
# 为queryset做序列化
class BookSerializers(serializers.Serializer):
"""Book表是一个比较复杂的表包含了一对多与多对多"""
title = serializers.CharField()
price = serializers.IntegerField()
pub_date = serializers.DateField()
# 这怎么办?
# publish = models.ForeignKey("Publish", on_delete=models.CASCADE) # 一对多
# authors = models.ManyToManyField("Author") # 多对多
publish = serializers.CharField(source="publish.name") # 一对多、类名小写
# 多对多的话这个sourse不好使,得到的是Queryset
# authors = serializers.CharField(source="authors.all") # 多对多、类名小写.all() 自动执行
# 多对多这样来整
authors = serializers.SerializerMethodField()
def get_authors(self, obj):
temp = []
for obj in obj.authors.all():
temp.append(obj.name)
return temp
class BookView(APIView):
def get(self, request):
book_list = Book.objects.all()
bs = BookSerializers(book_list, many=True)
return Response(bs.data)
def post(self, request):
pass
[
{
"title": "你好,再见",
"price": 99,
"pub_date": null,
"publish": "苹果出版社",
"authors": [
"pontoon",
"toonpon"
]
},
{
"title": "再见,你好",
"price": 88,
"pub_date": null,
"publish": "橘子出版社",
"authors": [
"pontoon"
]
},
{
"title": "谁动了我的奶酪?",
"price": 77,
"pub_date": null,
"publish": "苹果出版社",
"authors": []
}
]
# 为queryset做序列化
class BookSerializers(serializers.Serializer):
"""Book表是一个比较复杂的表包含了一对多与多对多"""
title = serializers.CharField()
price = serializers.IntegerField()
pub_date = serializers.DateField()
# 这怎么办?
# publish = models.ForeignKey("Publish", on_delete=models.CASCADE) # 一对多
# authors = models.ManyToManyField("Author") # 多对多
publish = serializers.CharField(source="publish.pk") # 一对多、类名小写
# 多对多的话这个sourse不好使,得到的是Queryset
# authors = serializers.CharField(source="authors.all") # 多对多、类名小写.all() 自动执行
# 多对多这样来整
authors = serializers.SerializerMethodField()
def get_authors(self, obj):
temp = []
for obj in obj.authors.all():
temp.append(obj)
return temp
# 这个地方我们对字段进行了一些列的定制
class BookView(APIView):
def get(self, request):
...
def post(self, request):
bs = BookSerializers(data=request.data)
if bs.is_valid(): # 验证码提交过来的数据是否合格
print(bs.validated_data) # 如果是合格的数据走了内置的create()方法,将提交过来的保存至数据库中!
bs.save() # 保存
return Response(bs.data) # 返回数据
else:
return Response(bs.errors) # 返回错误
class BookSerializers(serializers.ModelSerializer):
"""Book表是一个比较复杂的表包含了一对多与多对多"""
class Meta:
model = Book
fields = "__all__"
publish = serializers.CharField(source="publish.pk") # 一对多、类名小写
def create(self, validated_data):
"""重写源码中的create方法"""
print("validated_data", validated_data)
book = Book.objects.create(title=validated_data["title"],
price=validated_data[‘price‘],
publish_id=validated_data[‘publish‘][‘pk‘],
)
book.authors.add(*validated_data["authors"])
return book
>>> validated_data {‘publish‘: {‘pk‘: ‘1‘}, ‘title‘: ‘java‘, ‘price‘: 20, ‘authors‘: [<Author: pontoon>, <Author: toonpon>]}
class BookView(APIView):
def get(self, request):
book_list = Book.objects.all()
bs = BookSerializers(book_list, many=True)
return Response(bs.data)
def post(self, request):
bs = BookSerializers(data=request.data)
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return Response(bs.errors)
# 获取所有数据的URL
path(‘books/‘, views.BookView.as_view()),
# 获取单条数据的URL
path(‘books/<int:pk>‘, views.BookDetailView.as_view()),
class BookDetailView(APIView):
"""获取单条数据"""
def get(self, request, pk):
book = Book.objects.get(pk=pk)
bs = BookModelSerializers(book)
return Response(bs.data)
def put(self, request, pk):
""" 想那张表提交那条数据 """
book = Book.objects.get(pk=pk)
bs = BookModelSerializers(book, data=request.data)
if bs.is_valid():
bs.save()
return Response(bs.errors)
def delete(self, request, pk):
Book.objects.get(pk=pk).delete()
return Response()
标签:www. indent text api web api index tps cas size
原文地址:https://www.cnblogs.com/pontoon/p/10217408.html