激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - django rest framework之請求與響應(詳解)

django rest framework之請求與響應(詳解)

2020-12-16 00:17前程明亮 Python

下面小編就為大家帶來一篇django rest framework之請求與響應(詳解)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望對大家有所幫助

前言:在上一篇文章,已經實現了訪問指定URL就返回了指定的數據,這也體現了RESTful API的一個理念,每一個URL代表著一個資源。當然我們還知道RESTful API的另一個特性就是,發送不同的請求動作,會返還不同的響應,這篇文章就講一下django-rest-framework這個工具在這方面給我們帶來的便捷操作。

一、Request對象

平時我們在寫Django的視圖函數的時候,都會帶上一個request參數,這樣就能處理平時搭建網站時,瀏覽器訪問網頁時發出的常規的HttpRequest。但是現在我們導入了django-rest-framework,它能夠對request進行拓展,并且提供更靈活的請求解析。這個特性體現在哪呢?請看下面這個例子:

 
?
1
 
2
3
<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格式的響應,在視圖函數中是這樣的:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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對象就很方便了,它會根據客戶端的請求頭部信息來確定正確的內容類型以返回給客戶端。只需如下代碼:

 
?
1
 
2
<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類,所以繼續刪除。一旦完成,我們可以開始細微地重構我們的視圖。

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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格式的數據再進一步處理:

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

也就是說需要分成兩步實現,而且這里有一個限制就是只能解析json格式的數據流。而改進后的程序只需一行代碼:

 
?
1
 
2
<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格式了,由原本的:

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

改成了

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

這也意味著返回給客戶端的可以是json或者html等格式的內容,返回HTML格式的內容的話,會在瀏覽器返回經過渲染的、更美觀的頁面。同時可以看出狀態碼也改進成了django-rest-framework給我們帶來的可讀性更高的狀態標識碼,以上這些措施都很大程度的提高了對客戶的友好度。

對于另一個視圖函數的修改也是同樣的原理,這里就不做同樣的講解了,代碼如下:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@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:

 
?
1
 
def snippet_list(request, format=None):

and

 
?
1
 
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.

 
?
1
 
2
3
4
5
6
7
8
9
10
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.

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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:

 
?
1
 
2
<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:

 
?
1
 
2
<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.

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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之請求與響應(詳解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:http://www.cnblogs.com/0zcl/p/7787354.html

延伸 · 閱讀

精彩推薦
Weibo Article 1 Weibo Article 2 Weibo Article 3 Weibo Article 4 Weibo Article 5 Weibo Article 6 Weibo Article 7 Weibo Article 8 Weibo Article 9 Weibo Article 10 Weibo Article 11 Weibo Article 12 Weibo Article 13 Weibo Article 14 Weibo Article 15 Weibo Article 16 Weibo Article 17 Weibo Article 18 Weibo Article 19 Weibo Article 20 Weibo Article 21 Weibo Article 22 Weibo Article 23 Weibo Article 24 Weibo Article 25
主站蜘蛛池模板: 13一14毛片免费看 | 中文字幕免费看 | 成人免费观看av | 国产午夜精品一区二区三区四区 | 直接在线观看的三级网址 | 在线成人av观看 | 一区二区久久久久草草 | 9999精品 | 19禁国产精品福利视频 | 天天躁狠狠躁夜躁2020挡不住 | 欧美一级aa免费毛片 | 日日做夜夜操 | av成人免费| 一级毛片在线观看视频 | 免费黄色的视频 | 成人男女啪啪免费观看网站四虎 | 色网免费观看 | 91久久久久久 | 亚洲九色 | 久久国产精品小视频 | 日本视频免费看 | 中文字幕免费看 | 91久久国产露脸精品国产 | 黄色av.com| 国产一级免费在线视频 | 7m视频成人精品分类 | 日韩大片在线永久观看视频网站免费 | 7777在线视频免费播放 | 亚洲成人在线视频网 | 成人福利视频导航 | 成人aaaa免费全部观看 | 久久新网址 | 秋霞a级毛片在线看 | 国产91精品久久久久久久 | 羞羞答答tv | 91亚洲精品一区二区福利 | 亚洲视频在线网 | 美女羞羞视频网站 | 中日无线码1区 | 免费看日产一区二区三区 | 7777视频 |