Django REST framework 學(xué)習(xí)紀(jì)要 Tutorial 2 Requests and Responses

Request 對(duì)象

REST 框架引入了Request對(duì)象,繼承于HttpRequest,相比HttpRequest提供了更多請(qǐng)求解析,最核心的功能是request.data屬性,類(lèi)似于request.POST,以下是不同之處。

  • request.POST
  1. 只能處理form表單數(shù)據(jù);
  2. 只能處理POST請(qǐng)求。
  • request.data
  1. 能夠處理任意一種數(shù)據(jù);
  2. 能夠處理POST、PUT、PATCH請(qǐng)求

Response 對(duì)象

REST框架也引入了Response對(duì)象,它是一個(gè)TemplateResponse類(lèi)型,能夠?qū)⑽刺幚淼奈谋巨D(zhuǎn)換為合適的類(lèi)型返回給客戶端

return Response(data)

狀態(tài)碼

REST框架提供了更可讀的狀態(tài)信息,比如HTTP_400_BAD_REQUEST

API views封裝

  • 對(duì)于函數(shù)views,可以使用@api_view裝飾器
  • 對(duì)于類(lèi)views,可以繼承于APIView

views應(yīng)用

  • 修改snippets/views.py
  1. GET獲取所有code snippets,與新建code snippet的接口
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


@api_view(['GET', 'POST'])
def snippet_list(request):
    """
    list all code snippets, or create a new snippet
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  1. GET獲取單個(gè)code snippet,PUT更新單個(gè)code snippet,DELETE刪除單個(gè)code snippet
@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
    """
    retrieve, update or delete code snippet
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoseNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

和上一步的views明顯不同的是,我們不再需要關(guān)心輸入(request)輸出(response)的數(shù)據(jù)類(lèi)型,REST框架已經(jīng)幫我們處理好了

為URLs添加可選格式后綴

如上一步所說(shuō)的,REST框架已經(jīng)幫我們處理好了輸入(request)輸出(response)的數(shù)據(jù)類(lèi)型,也就意味著一個(gè)API可以去處理不同的數(shù)據(jù)類(lèi)型,在URLs中使用格式后綴可以幫助我們處理類(lèi)似這樣的url: http://192.168.0.103/snippets.json

  • 首先我們需要在views中添加形參format=None
def snippet_list(request, format=None):

def snippet_list(request, format=None):
  • 然后我們修改urls.py
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = [
    url(r'^snippets/$', views.snippet_list),
    url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
]

urlpatterns = format_suffix_patterns(urlpatterns)

調(diào)用接口

  • 在啟動(dòng)服務(wù)器前,先修改settings.py中的ALLOWED_HOSTS,方便后面通過(guò)外部瀏覽器請(qǐng)求接口
ALLOWED_HOSTS = ['*']
  • 啟動(dòng)服務(wù)器(別管時(shí)間,每天晚上回來(lái),讓W(xué)in10從睡眠狀態(tài)恢復(fù),虛擬機(jī)的IP和時(shí)區(qū)總會(huì)變 :( ,懶得每次都改了)
(django_rest_framework) [root@localhost tutorial]# python manage.py runserver 0:80
Performing system checks...

System check identified no issues (0 silenced).
November 21, 2017 - 02:47:02
Django version 1.11.7, using settings 'tutorial.settings'
Starting development server at http://0:80/
Quit the server with CONTROL-C.
  • 打開(kāi)另一個(gè)shell窗口,發(fā)送請(qǐng)求
(django_rest_framework) [root@localhost django_rest_framework]# http http://127.0.0.1:80/snippets/
HTTP/1.0 200 OK
Allow: POST, GET, OPTIONS
Content-Length: 505
Content-Type: application/json
Date: Mon, 20 Nov 2017 18:51:07 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

[
    {
        "code": "foo = \"bar\n\"",
        "id": 1,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
    {
        "code": "print \"hello, world\"\n",
        "id": 2,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
...
]
  • 我們可以添加HTTP HEADERS來(lái)控制返回?cái)?shù)據(jù)的數(shù)據(jù)類(lèi)型
  1. json
(django_rest_framework) [root@localhost django_rest_framework]# http http://127.0.0.1:80/snippets/ Accept:application/json
HTTP/1.0 200 OK
Allow: POST, GET, OPTIONS
Content-Length: 505
Content-Type: application/json
Date: Mon, 20 Nov 2017 18:52:27 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

[
    {
        "code": "foo = \"bar\n\"",
        "id": 1,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
    {
        "code": "print \"hello, world\"\n",
        "id": 2,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
]
  1. html
(django_rest_framework) [root@localhost django_rest_framework]# http http://127.0.0.1:80/snippets/ Accept:text/html
HTTP/1.0 200 OK
Allow: POST, GET, OPTIONS
Content-Length: 8139
Content-Type: text/html; charset=utf-8
Date: Mon, 20 Nov 2017 18:53:39 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

<!DOCTYPE html>
<html>
  <head>
    

      
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta name="robots" content="NONE,NOARCHIVE" />
      

      <title>Snippet List – Django REST framework</title>

      
        
          <link rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap.min.css"/>
...
  • 或者我們直接可以添加url后綴來(lái)控制返回?cái)?shù)據(jù)的數(shù)據(jù)類(lèi)型
  1. json
(django_rest_framework) [root@localhost django_rest_framework]# http http://127.0.0.1:80/snippets.json
HTTP/1.0 200 OK
Allow: POST, GET, OPTIONS
Content-Length: 505
Content-Type: application/json
Date: Mon, 20 Nov 2017 18:55:27 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

[
    {
        "code": "foo = \"bar\n\"",
        "id": 1,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
    {
        "code": "print \"hello, world\"\n",
        "id": 2,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
...
]
  1. html
(django_rest_framework) [root@localhost django_rest_framework]# http http://127.0.0.1:80/snippets.api
HTTP/1.0 200 OK
Allow: POST, GET, OPTIONS
Content-Length: 8160
Content-Type: text/html; charset=utf-8
Date: Mon, 20 Nov 2017 18:56:35 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

<!DOCTYPE html>
<html>
  <head>
    

      
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta name="robots" content="NONE,NOARCHIVE" />
      

      <title>Snippet List – Django REST framework</title>

      
        
          <link rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap.min.css"/>
          <link rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap-tweaks.css"/>
...
  • 類(lèi)似的,我們可以發(fā)送不同類(lèi)型的數(shù)據(jù)給API
  1. post form data
(django_rest_framework) [root@localhost django_rest_framework]# http --form POST http://127.0.0.1:80/snippets/ code="hello world post form data"
HTTP/1.0 201 Created
Allow: POST, GET, OPTIONS
Content-Length: 110
Content-Type: application/json
Date: Mon, 20 Nov 2017 18:58:58 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

{
    "code": "hello world post form data",
    "id": 6,
    "language": "python",
    "linenos": false,
    "style": "friendly",
    "title": ""
}
  1. post json data
(django_rest_framework) [root@localhost django_rest_framework]# http --json POST http://127.0.0.1:80/snippets/ code="hello world post json data"
HTTP/1.0 201 Created
Allow: POST, GET, OPTIONS
Content-Length: 110
Content-Type: application/json
Date: Mon, 20 Nov 2017 18:59:44 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

{
    "code": "hello world post json data",
    "id": 7,
    "language": "python",
    "linenos": false,
    "style": "friendly",
    "title": ""
}
  • 在請(qǐng)求時(shí)添加--debug后綴可以查看請(qǐng)求的詳細(xì)信息
(django_rest_framework) [root@localhost django_rest_framework]# http --json POST http://127.0.0.1:80/snippets/ code="hello world post json data" --debug
HTTPie 0.9.9
Requests 2.18.4
Pygments 2.2.0
Python 3.6.3 (default, Nov  4 2017, 22:19:41) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
/root/.pyenv/versions/3.6.3/envs/django_rest_framework/bin/python
Linux 3.10.0-693.el7.x86_64

<Environment {
    "colors": 8,
    "config": {
        "__meta__": {
            "about": "HTTPie configuration file",
            "help": "https://httpie.org/docs#config",
            "httpie": "0.9.9"
        },
        "default_options": "[]"
    },
    "config_dir": "/root/.httpie",
    "is_windows": false,
    "stderr": "<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>",
    "stderr_isatty": true,
    "stdin": "<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>",
    "stdin_encoding": "UTF-8",
    "stdin_isatty": true,
    "stdout": "<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>",
    "stdout_encoding": "UTF-8",
    "stdout_isatty": true
}>

>>> requests.request(**{
    "allow_redirects": false,
    "auth": "None",
    "cert": "None",
    "data": "{\"code\": \"hello world post json data\"}",
    "files": {},
    "headers": {
        "Accept": "application/json, */*",
        "Content-Type": "application/json",
        "User-Agent": "HTTPie/0.9.9"
    },
    "method": "post",
    "params": {},
    "proxies": {},
    "stream": true,
    "timeout": 30,
    "url": "http://127.0.0.1:80/snippets/",
    "verify": true
})

HTTP/1.0 201 Created
Allow: POST, GET, OPTIONS
Content-Length: 110
Content-Type: application/json
Date: Mon, 20 Nov 2017 19:00:45 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

{
    "code": "hello world post json data",
    "id": 9,
    "language": "python",
    "linenos": false,
    "style": "friendly",
    "title": ""
}
  • 在瀏覽器中發(fā)送請(qǐng)求
  1. 在瀏覽器中發(fā)送請(qǐng)求,默認(rèn)會(huì)返回html類(lèi)型的數(shù)據(jù)
  1. 可以像之前那樣,加上url后綴,來(lái)請(qǐng)求json數(shù)據(jù)

關(guān)于

本人是初學(xué)Django REST framework,Django REST framework 學(xué)習(xí)紀(jì)要系列文章是我從官網(wǎng)文檔學(xué)習(xí)后的初步消化成果,如有錯(cuò)誤,歡迎指正。

學(xué)習(xí)用代碼Github倉(cāng)庫(kù):shelmingsong/django_rest_framework

本文參考的官網(wǎng)文檔:Tutorial 2: Requests and Responses

博客更新地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,568評(píng)論 19 139
  • Django: csrf防御機(jī)制 csrf攻擊過(guò)程 1.用戶C打開(kāi)瀏覽器,訪問(wèn)受信任網(wǎng)站A,輸入用戶名和密碼請(qǐng)求登...
    lijun_m閱讀 1,151評(píng)論 0 0
  • Tutorial 1: Serialization 序列化 安裝基本環(huán)境 開(kāi)始 創(chuàng)建測(cè)試環(huán)境 創(chuàng)建一個(gè) djang...
    Passon_Fang閱讀 4,333評(píng)論 2 8
  • 目前我們使用主鍵來(lái)表示模型之間的關(guān)系。在本章,我們將提高API的凝聚性和可讀性。 為我們API的根節(jié)點(diǎn)創(chuàng)建URL ...
    流月0閱讀 479評(píng)論 0 0
  • 前兩天看了一本書(shū),叫《少有人走的路 勇敢地面對(duì)謊言》,寫(xiě)的主要是作者作為心理醫(yī)生診斷病人的案例及感悟。 第一章講...
    親愛(ài)的廢柴閱讀 348評(píng)論 0 1

友情鏈接更多精彩內(nèi)容