django rest-framework 2.請求和響應

1、請求對象

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

導入方式: from rest_framework.response import Requestpython

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

2、響應對象

REST框架還引入了一個Response對象,它是一種類型的對象,它TemplateResponse採用未呈現的內容,並使用內容協商來肯定正確的內容類型以返回給客戶端。django

return Response(data)  # Renders to content type as requested by the client.

3、狀態碼

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

導入方式: from rest_framework import statusapi

4、視圖裝飾器

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.app

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.框架

5、Pulling it all together

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

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)

 6、添加可選的後綴格式

利用REST響應再也不是單一的內容類型,能夠爲API添加對格式後綴的支持,使用格式後綴顯示指定格式的返回內容

首先須要在兩個視圖函數添加一個關鍵字參數 format ,以下:

def game_list(request, format=None):
def game_info(request, game_id, format=None):

在urls.py中稍微修改文件,在現有的URL以外還附加一組 format_suffix_patterns

from django.conf.urls import url
from test_app import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    url(r'^game_list/',views.game_list),
    url(r'^game_info/(\d+)/', views.game_info),
]
urlpatterns = format_suffix_patterns(urlpatterns)

咱們不必定須要添加這些額外的url模式,但它給了咱們一個簡單,乾淨的方式來引用特定的格式。

7、如何使用可選的格式後綴

1. 經過 Accept 頭來控制回覆的格式:

http http://127.0.0.1:8000/game_list/ Accept:application/json  # Request JSON
http http://127.0.0.1:8000/game_list/ Accept:text/html         # Request HTML

2. 經過附加格式後綴

http http://127.0.0.1:8000/game_list.json  # JSON suffix
http http://127.0.0.1:8000/game_list.api   # Browsable API suffix

3. Content-Type 頭控制發送的請求格式    http://www.django-rest-framework.org/tutorial/2-requests-and-responses/

# 參考官網
# POST using form data
http --form POST http://127.0.0.1:8000/snippets/ code="print 123"

{
  "id": 3,
  "title": "",
  "code": "print 123",
  "linenos": false,
  "language": "python",
  "style": "friendly"
}

# POST using JSON
http --json POST http://127.0.0.1:8000/snippets/ code="print 456"

{
    "id": 4,
    "title": "",
    "code": "print 456",
    "linenos": false,
    "language": "python",
    "style": "friendly"
}

8、WEB功能

因爲API根據客戶端請求選擇響應的內容類型,所以默認狀況下,當Web瀏覽器請求該資源時,它將返回資源的HTML格式表示。這容許API返回徹底可瀏覽網頁的HTML表示。

擁有可瀏覽網頁的API是一個巨大的可用性勝利,並使開發和使用您的API更容易。它也大大下降了其餘開發人員檢查和使用API​​的障礙。

有關瀏覽的API功能以及如何自定義API的更多信息,請參閱可瀏覽的api主題。

相關文章
相關標籤/搜索