1. 程式人生 > >django rest-framework 2.請求和響應

django rest-framework 2.請求和響應

str val cor 之前 man .post 狀態碼 del exc

一、請求對象

REST 框架引入Request來擴展常規的HttpRequest,並提供了更靈活的請求解析。Request對象的核心功能是request.data屬性。

導入方式: from rest_framework.response import Response

request.POST  # Only handles form data.  Only works for ‘POST‘ method.
request.data  # Handles arbitrary data.  Works for ‘POST‘, ‘PUT‘ and ‘PATCH‘ methods.

二、響應對象

三、狀態碼

在Response返回中使用數字HTTP狀態碼並不總是有助於明顯的閱讀,REST框架為每一個狀態碼更明確的標識符,如 HTTP_404_NOT_FOUND 。

導入方式: from rest_framework import status

四、視圖裝飾器

REST框架提供了兩個可用於編寫API視圖的裝飾器

  • @api_view # 函數裝飾器
  • APIView   # 類裝飾器

These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response

objects so that content negotiation can be performed.

The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exception that occurs when accessing request.data with malformed input.

五、Pulling it all together

這裏不在需要使用JSONResponse來格式化返回數據

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from test_app import serializer
from test_app import models


@api_view([‘GET‘, ‘POST‘])
def game_list(request):
    if request.method == ‘GET‘:
        games = models.Game.objects.all()
        games_serializer = serializer.Test_app_model_serializer(instance=games, many=True)
        return Response(games_serializer.data)
    elif request.method == ‘POST‘:
        game_serializer = serializer.Test_app_model_serializer(data=request.data)
        if game_serializer.is_valid():
            game_serializer.save()
            return Response(game_serializer.data, status=status.HTTP_201_CREATED)
        return Response(game_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

想相對於之前寫的視圖函數,這樣更加簡明扼要,這裏是@api_view裝飾器的功勞。

這是views.py模塊中裏一個視圖代碼

@api_view([‘GET‘, ‘PUT‘, ‘DELETE‘])
def game_info(request, game_id):
    try:
        game_obj = models.Game.objects.get(id=game_id)
    except models.Game.DoesNotExist as e:
        return Response(status=status.HTTP_404_NOT_FOUND)
        # return HttpResponse(e,status=status.HTTP_404_NOT_FOUND)
    if request.method == ‘GET‘:
        game_serializer = serializer.Test_app_model_serializer(instance=game_obj)
        return Response(game_serializer.data)
    elif request.method == ‘PUT‘:
        game_serializer = serializer.Test_app_model_serializer(instance=game_obj,data=request.data)
        if game_serializer.is_valid():
            game_serializer.save()
            return Response(game_serializer.data)
        return Response(game_serializer.errors)
    elif request.method == ‘DELETE‘:
        game_obj.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

離開家按理說發動機

django rest-framework 2.請求和響應