Request 對(duì)象
REST 框架引入了Request對(duì)象,繼承于HttpRequest,相比HttpRequest提供了更多請(qǐng)求解析,最核心的功能是request.data屬性,類(lèi)似于request.POST,以下是不同之處。
request.POST
- 只能處理form表單數(shù)據(jù);
- 只能處理POST請(qǐng)求。
request.data
- 能夠處理任意一種數(shù)據(jù);
- 能夠處理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
-
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)
-
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)型
- 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": ""
},
]
- 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)型
- 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": ""
},
...
]
- 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
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": ""
}
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)求
- 在瀏覽器中發(fā)送請(qǐng)求,默認(rèn)會(huì)返回html類(lèi)型的數(shù)據(jù)
- 可以像之前那樣,加上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
博客更新地址
- 宋明耀的博客 [ 第一時(shí)間更新 ]
- 知乎專(zhuān)欄 Python Cookbook
- 簡(jiǎn)書(shū) 流月0的文章