django rest_framework入门三-Requests和Responses
这一节,我们介绍rest_framework的Requests和Responses对象,来替代django.http的HttpRequest和HttpResponse对象
1.Requests和Responses对象的特点
1)Request对象
request.data #处理任意数据,接收'POST','PUT'和'PATCH'方法。
2)Response对象
HttpResponse只能返回string,而Response可以对任意类型自动处理,更加方便。
3)状态码
rest_framework提供了状态码,使用它们替换数字可读性更强。
2.rest_framework编写视图
rest_framework提供了两种方法来编写视图:
1)基于函数视图的@api_view装饰器
2)基于类视图的APIView
3.使用示例
import json
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
# Create your views here.
@api_view(['GET', 'POST'])
def snippet_list(request):
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
result_type = type(serializer.data)
result = serializer.data
return Response(result)
if request.method == 'POST':
data = request.data
serializer = SnippetSerializer(data=data)
if serializer.is_valid():
serializer.save()
result = json.dumps(serializer.data)
return Response(result, status = status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
可以对比和上节使用django的HttpResponse的区别,其实不大,个人觉得差别不大