django rest framework之请求与响应(详解)


Posted in Python onNovember 06, 2017

前言:在上一篇文章,已经实现了访问指定URL就返回了指定的数据,这也体现了RESTful API的一个理念,每一个URL代表着一个资源。当然我们还知道RESTful API的另一个特性就是,发送不同的请求动作,会返还不同的响应,这篇文章就讲一下django-rest-framework这个工具在这方面给我们带来的便捷操作。

一、Request对象

平时我们在写Django的视图函数的时候,都会带上一个request参数,这样就能处理平时搭建网站时,浏览器访问网页时发出的常规的HttpRequest。但是现在我们导入了django-rest-framework,它能够对request进行拓展,并且提供更灵活的请求解析。这个特性体现在哪呢?请看下面这个例子:

<SPAN style="FONT-SIZE: 13px">request.POST # Only handles <SPAN style="COLOR: #ff0000">form data</SPAN>. Only works for '<SPAN style="COLOR: #ff0000">POST</SPAN>' method. 
request.data # Handles <SPAN style="COLOR: #ff0000">arbitrary(任意的) data</SPAN>. Works for '<SPAN style="COLOR: #ff0000">POST', 'PUT' and 'PATCH</SPAN>' methods. 
</SPAN>

request.POST只能处理前端发起的POST请求,只能处理表单提交的数据。而request.data可以处理任意数据,而不单单是前端提交的表单数据,可用于post, put, patch请求。

二、Response对象

和request对象一样,django-rest-framework也对其进行了很实用的拓展,在我上一篇文章的snippets/views.py中,我们导入了JsonResponse用于返回json格式的响应,在视图函数中是这样的:

@csrf_exempt
def snippet_list(request):
 """
 because we want to be able to POST to this view from clients
 that won't have a CSRF token we need to mark the view as csrf_exempt
 List all code snippets, or create a new snippet.
 """
 if request.method == "GET":
  snippets = Snippet.objects.all()
  serializer = SnippetSerializer(snippets, many=True)
  return JsonResponse(serializer.data, safe=False)

 elif request.method == "POST":
  data = JSONParser().parse(request)
  serializer = SnippetSerializer(data=data)
  if serializer.is_valid():
   serializer.save()
   return JsonResponse(serializer.data, status=201)
  return JsonResponse(serializer.errors, status=400)

也就是说,在return的时候就需要指明json格式,这样显得很不实用而且很单一,所以经过拓展后的Reponse对象就很方便了,它会根据客户端的请求头部信息来确定正确的内容类型以返回给客户端。只需如下代码:

<SPAN style="FONT-SIZE: 13px">return Response(data) # <SPAN style="COLOR: #ff0000">Renders to content type as requested by the client. 
</SPAN></SPAN>

三、状态码

我们知道发送http请求时会返回各种各样的状态吗,但是都是简单的数字,比如200、404等,这些纯数字标识符有时候可能不够明确或者客户端在使用的时候不清楚错误信息甚至是没注意看不到,所以django-rest-framework也对此进行了优化,状态码会是HTTP_400_BAD_REQUEST、HTTP_404_NOT_FOUND这种,极大的提高可读性

四、包装API视图

REST框架提供了两个可用于编写API视图的包装器。

•@api_view装饰器用于处理基于函数的视图

•APIView类用在基于视图的类上

这些包装提供了一些功能,让我们省去很多工作。比如说确保你在视图中收到Request对象或在你的Response对象中添加上下文,这样就能实现内容通信。

另外装饰器可以在接收到输入错误的request.data时抛出ParseError异常,或者在适当的时候返回405 Method Not Allowed状态码。

五、Pulling it all together(使用)

Okay, let's go ahead and start using these new components to write a few views.

We don't need our JSONResponse class in views.py any more, so go ahead and delete that. Once that's done we can start refactoring(重构) our views slightly.

在views.py文件中我们不再需要我们的JSONResponse类,所以继续删除。一旦完成,我们可以开始细微地重构我们的视图。

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)

可以看出,经过改进的代码已经把上面所说的几个django-rest-framework带来的特性都应用起来了,我们可以看出程序代码量变少,并且能处理的情况更多了。 比如说,在原本的视图函数snippet_detail中,处理'PUT'请求的时候,需要先解析前端发来的json格式的数据再进一步处理:

<SPAN style="FONT-SIZE: 13px">data = JSONParser().parse(request) 
serializer = SnippetSerializer(snippet, data=data) 
</SPAN>

也就是说需要分成两步实现,而且这里有一个限制就是只能解析json格式的数据流。而改进后的程序只需一行代码:

<SPAN style="FONT-SIZE: 13px">serializer = SnippetSerializer(data=request.data) 
</SPAN>

request.data can handle incoming json requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.

request.data就可以获取到提交过来的数据了,并且可以处理各种数据和各种请求动作,方便了开发。还有在return的时候也不需要指定json格式了,由原本的:

<SPAN style="FONT-SIZE: 13px">return JsonResponse(serializer.data, status=201) 
</SPAN>

改成了

<SPAN style="FONT-SIZE: 13px">return Response(serializer.data,status=status.HTTP_201_CREATED) 
</SPAN>

这也意味着返回给客户端的可以是json或者html等格式的内容,返回HTML格式的内容的话,会在浏览器返回经过渲染的、更美观的页面。同时可以看出状态码也改进成了django-rest-framework给我们带来的可读性更高的状态标识码,以上这些措施都很大程度的提高了对客户的友好度。

对于另一个视图函数的修改也是同样的原理,这里就不做同样的讲解了,代码如下:

@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
 """
 Retrieve, update or delete a code snippet.
 """
 try:
  snippet = Snippet.objects.get(pk=pk)
 except Snippet.DoesNotExist:
  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.data)
  return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

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

以上就是对原有的常规的Django视图函数的改进。

总结一下就是处理request提交过来的数据不需要一定是json格式的数据,返回的响应也不需要一定是json数据,也可以是经过渲染的HTML页面。稍后就会示范使用。

六、向URL添加可选的格式后缀

既然上面已经说了返回给客户端的Response可是json或者是HTML等格式的内容,那么用户在使用的时候是如何指定返回哪种格式的内容呢,那就是在URL的最后加上后缀。比如http://127.0.0.1:8000/snippets.json,这样就是用户自己指定了返回json格式的Response,而不是我们在后台指定返回固定的格式。

只需对我们的程序稍加改进就可以了,在两个视图函数添加关键词参数format:

def snippet_list(request, format=None):

and

def snippet_detail(request, pk, format=None):

Now update the urls.py file slightly, to append a set of format_suffix_patterns(格式后缀模式) in addition to the existing URLs.

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)

七、How's it looking?

Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.

We can get a list of all of the snippets, as before.

http http://127.0.0.1:8000/snippets/

HTTP/1.1 200 OK
...
[
 {
 "id": 1,
 "title": "",
 "code": "foo = \"bar\"\n",
 "linenos": false,
 "language": "python",
 "style": "friendly"
 },
 {
 "id": 2,
 "title": "",
 "code": "print \"hello, world\"\n",
 "linenos": false,
 "language": "python",
 "style": "friendly"
 }
]

We can control the format of the response that we get back, either by using the Accept header:

<SPAN style="FONT-SIZE: 13px">http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON 
http http://127.0.0.1:8000/snippets/ Accept:text/html   # Request HTML</SPAN>

Or by appending a format suffix:

<SPAN style="FONT-SIZE: 13px">http http://127.0.0.1:8000/snippets.json # JSON suffix 
http http://127.0.0.1:8000/snippets.api # Browsable API suffix</SPAN>

Similarly, we can control the format of the request that we send, using the Content-Type header.

# 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"
}

If you add a --debug switch to the http requests above, you will be able to see the request type in request headers.

Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.

Browsability

Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.

Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.

See the browsable api topic for more information about the browsable API feature and how to customize it.

浏览功能(中文)

由于API根据客户端请求选择响应的内容类型,因此默认情况下,当Web浏览器请求资源时,将返回HTML格式的资源表示形式。这允许API返回完全的可浏览网页的HTML表示。

拥有一个可浏览网页的API是一个巨大的可用性胜利,并且使开发和使用您的API更容易。它也大大降低了想要检查和使用您的API的其他开发人员的入门障碍。

有关可浏览的API功能以及如何对其进行定制的更多信息,请参阅可浏览的api主题。

以上这篇django rest framework之请求与响应(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python最长公共子串算法实例
Mar 07 Python
python中的代码编码格式转换问题
Jun 10 Python
Python的包管理器pip更换软件源的方法详解
Jun 20 Python
Python队列的定义与使用方法示例
Jun 24 Python
Python3 queue队列模块详细介绍
Jan 05 Python
Python决策树和随机森林算法实例详解
Jan 30 Python
python3 遍历删除特定后缀名文件的方法
Apr 23 Python
Python基于滑动平均思想实现缺失数据填充的方法
Feb 21 Python
正则给header的冒号两边参数添加单引号(Python请求用)
Aug 09 Python
python生成并处理uuid的实现方式
Mar 03 Python
python使用Word2Vec进行情感分析解析
Jul 31 Python
mac安装python3后使用pip和pip3的区别说明
Sep 01 Python
基于python中的TCP及UDP(详解)
Nov 06 #Python
利用Python循环(包括while&amp;for)各种打印九九乘法表的实例
Nov 06 #Python
利用Tkinter和matplotlib两种方式画饼状图的实例
Nov 06 #Python
django实现登录时候输入密码错误5次锁定用户十分钟
Nov 05 #Python
用Python登录好友QQ空间点赞的示例代码
Nov 04 #Python
Python通过命令开启http.server服务器的方法
Nov 04 #Python
Python实现一个简单的验证码程序
Nov 03 #Python
You might like
PHP4和PHP5共存于一系统
2006/11/17 PHP
phpStudy中升级MySQL版本到5.7.17的方法步骤
2017/08/03 PHP
javaScript 判断字符串是否为数字的简单方法
2009/07/25 Javascript
理解 JavaScript 预解析
2009/10/25 Javascript
javascript针对DOM的应用实例(一)
2012/04/15 Javascript
js通过元素class名字获取元素集合的具体实现
2014/01/06 Javascript
JS获取文本框,下拉框,单选框的值的简单实例
2014/02/26 Javascript
Jquery简单实现GridView行高亮的方法
2015/06/15 Javascript
AngularJS中的$watch(),$digest()和$apply()区分
2016/04/04 Javascript
使用jQuery中的wrap()函数操作HTML元素的教程
2016/05/24 Javascript
EasyUI Pagination 分页的两种做法小结
2016/07/09 Javascript
Angular2中Bootstrap界面库ng-bootstrap详解
2016/10/18 Javascript
bootstrap table操作技巧分享
2017/02/15 Javascript
jQuery阻止移动端遮罩层后页面滚动
2017/03/15 Javascript
解决VUE双向绑定失效的问题
2019/10/29 Javascript
微信小程序中限制激励式视频广告位显示次数(实现思路)
2019/12/06 Javascript
[03:38]2014DOTA2西雅图国际邀请赛 VG战队巡礼
2014/07/07 DOTA
Python中操作MySQL入门实例
2015/02/08 Python
Django日志模块logging的配置详解
2017/02/14 Python
Python生成任意范围任意精度的随机数方法
2018/04/09 Python
python中多层嵌套列表的拆分方法
2018/07/02 Python
python 文件查找及内容匹配方法
2018/10/25 Python
浅谈python函数调用返回两个或多个变量的方法
2019/01/23 Python
Python中使用遍历在列表中添加字典遇到的坑
2019/02/27 Python
Python3.5以上版本lxml导入etree报错的解决方案
2019/06/26 Python
Django 再谈一谈json序列化
2020/03/16 Python
HTML5实现的震撼3D焦点图动画的示例代码
2019/09/26 HTML / CSS
小学生自我评价范例
2013/09/24 职场文书
自动化专业大学生职业生涯规划范文:爱拚才会赢
2014/09/12 职场文书
知识就是力量演讲稿
2014/09/13 职场文书
乡镇党的群众路线教育实践活动剖析材料
2014/10/09 职场文书
论群众路线学习心得体会
2014/10/31 职场文书
2015年科室工作总结
2015/04/10 职场文书
网吧管理制度范本
2015/08/05 职场文书
《钓鱼的启示》教学反思
2016/02/18 职场文书
教师学期述职自我鉴定
2019/08/16 职场文书