django rest_framework(三)——Requests和Responses

 

1.Requests和Responses對象的特色
1)Request對象
request.data #處理任意數據,接收'POST','PUT'和'PATCH'方法。
2)Response對象
HttpResponse只能返回string,而Response能夠對任意類型自動處理,更加方便。
3)狀態碼
rest_framework提供了狀態碼,使用它們替換數字可讀性更強。python

2.rest_framework編寫視圖
rest_framework提供了兩種方法來編寫視圖:
1)基於函數視圖的@api_view裝飾器
2)基於類視圖的APIViewjson

3.使用示例api

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)
相關文章
相關標籤/搜索