REST 框架引入了Request
对象,继承于HttpRequest
,相比HttpRequest
提供了更多请求解析,最核心的功能是request.data
属性,类似于request.POST
,以下是不同之处。
request.POST
request.data
REST框架也引入了Response
对象,它是一个TemplateResponse
类型,能够将未处理的文本转换为合适的类型返回给客户端
return Response(data)
REST框架提供了更可读的状态信息,比如HTTP_400_BAD_REQUEST
views
,可以使用@api_view
装饰器views
,可以继承于APIView
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
获取单个code snippet
,PUT
更新单个code snippet
,DELETE
删除单个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
明显不同的是,我们不再需要关心输入(request
)输出(response
)的数据类型,REST框架已经帮我们处理好了
如上一步所说的,REST框架已经帮我们处理好了输入(request
)输出(response
)的数据类型,也就意味着一个API可以去处理不同的数据类型,在URLs中使用格式后缀可以帮助我们处理类似这样的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[0-9]+)$' , views.snippet_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns)
settings.py
中的ALLOWED_HOSTS
,方便后面通过外部浏览器请求接口ALLOWED_HOSTS = ['*']
(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.
(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": ""
},
...
]
(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": ""
},
]
(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
="Content-Type" content="text/html; charset=utf-8"/>
name="robots" content="NONE,NOARCHIVE" />
Snippet List – Django REST framework
rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap.min.css"/>
...
(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": ""
},
...
]
(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
="Content-Type" content="text/html; charset=utf-8"/>
name="robots" content="NONE,NOARCHIVE" />
Snippet List – Django REST framework
rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap.min.css"/>
rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap-tweaks.css"/>
...
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": ""
}
--debug
后缀可以查看请求的详细信息(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
{
"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='' mode='w' encoding='UTF-8'>" ,
"stderr_isatty": true,
"stdin": "<_io.TextIOWrapper name='' mode='r' encoding='UTF-8'>" ,
"stdin_encoding": "UTF-8",
"stdin_isatty": true,
"stdout": "<_io.TextIOWrapper name='' 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": ""
}
本人是初学Django REST framework,Django REST framework 学习纪要系列文章是我从官网文档学习后的初步消化成果,如有错误,欢迎指正。
学习用代码Github仓库:shelmingsong/django_rest_framework
本文参考的官网文档:Tutorial 2: Requests and Responses