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中文编码那些事
Jun 25 Python
Python出现segfault错误解决方法
Apr 16 Python
Python 中的with关键字使用详解
Sep 11 Python
使用python装饰器计算函数运行时间的实例
Apr 21 Python
对Python 3.5拼接列表的新语法详解
Nov 08 Python
Django生成PDF文档显示在网页上以及解决PDF中文显示乱码的问题
Jul 04 Python
python项目对接钉钉SDK的实现
Jul 15 Python
Python中的上下文管理器相关知识详解
Sep 19 Python
Python FTP文件定时自动下载实现过程解析
Nov 12 Python
OpenCV+python实现实时目标检测功能
Jun 24 Python
Python importlib模块重载使用方法详解
Oct 13 Python
使用django自带的user做外键的方法
Nov 30 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
php下MYSQL limit的优化
2008/01/10 PHP
php通过数组实现多条件查询实现方法(字符串分割)
2014/05/06 PHP
Windows下的PHP 5.3.x安装 Zend Guard Loader教程
2014/09/06 PHP
php实现根据词频生成tag云的方法
2015/04/17 PHP
php采集中国代理服务器网的方法
2015/06/16 PHP
深入理解php printf() 输出格式化的字符串
2016/05/23 PHP
通过修改Laravel Auth使用salt和password进行认证用户详解
2017/08/17 PHP
PHP支付宝当面付2.0代码
2018/12/21 PHP
JS下高效拼装字符串的几种方法比较与测试代码
2010/04/15 Javascript
jQuery实战之仿淘宝商城左侧导航效果
2011/04/12 Javascript
setInterval,setTimeout与jquery混用的问题
2013/04/08 Javascript
jQuery删除节点的三个方法即remove()detach()和empty()
2013/12/27 Javascript
jquery选择checked在ie8普通模式下的问题
2014/02/12 Javascript
js+html5实现canvas绘制圆形图案的方法
2015/06/05 Javascript
jQuery实现下拉加载功能实例代码
2016/04/01 Javascript
修改jquery中dialog的title属性方法(推荐)
2016/08/26 Javascript
微信小程序 form组件详解
2016/10/25 Javascript
Angular的MVC和作用域
2016/12/26 Javascript
vue表单绑定实现多选框和下拉列表的实例
2017/08/12 Javascript
Redux 和 Mobx的选择问题:让你不再困惑!
2017/09/18 Javascript
bootstrap 弹出框modal添加垂直方向滚轴效果
2018/07/09 Javascript
vue路由权限校验功能的实现代码
2020/06/07 Javascript
Python素数检测实例分析
2015/06/15 Python
Python编程中使用Pillow来处理图像的基础教程
2015/11/20 Python
简述Python2与Python3的不同点
2018/01/21 Python
基于python 二维数组及画图的实例详解
2018/04/03 Python
python保留小数位的三种实现方法
2020/01/07 Python
Python递归函数特点及原理解析
2020/03/04 Python
canvas学习笔记之绘制简单路径
2019/01/28 HTML / CSS
英国女性化妆品收纳和家具网站:Beautify
2019/12/07 全球购物
简述索引存取方法的作用和建立索引的原则
2013/03/26 面试题
先进集体事迹材料
2014/02/17 职场文书
暑假社会实践证明格式
2014/10/28 职场文书
办公用房租赁协议书
2014/11/29 职场文书
vue3中的组件间通信
2021/03/31 Vue.js
Javascript中的解构赋值语法详解
2021/04/02 Javascript