以前按照REST Framework官方文檔提供的簡介寫了一系列的簡單的介紹博客,說白了就是翻譯了一下簡介,並且翻譯的很爛。到真正的生產時,就會發現很雞肋,連熟悉大概知道rest framework都不算,反正樓主看來,要想真正的將rest玩弄於股掌以內,很明顯,那一份樣例是遠遠不夠的。因此開闢一個新的REST Framework API Guide系列,這在rest framework的官方文檔也仍是有的,並且,不用想它是最全面的。這邊這個系列的主要目的是爲了本身可以抓住生產上的重點,從代碼實例上來講明問題,真正的作到關注實例,關注代碼。固然若是想看全面的教程建議仍是看django rest framework官方文檔,那個絕對是最權威的。前端
但願你們都能堅持,都能努力,支撐住野心的只有如今的行動,不積跬步無以致千里。加油。django
內容大綱 api
一、requestssession
二、response架構
三、CBV APIViewapp
四、FBV @api_view框架
.dataide
在rest framework中,對於以前咱們所習慣的FBV的格式寫法的request的結構進行了改造,今後之後,不須要再去request.GET或則會request.POST取獲取必要的參數了。全部的數據基本均可以在request.data內部獲取到,注意這裏是幾乎全部的,但不是所有。函數
.query_paramspost
這裏就要去除掉一部分request的數據了,url裏面?name=value的查詢參數之類的從self.query_params獲取。
.user
這是一個認證相關的請求數據,若是認證經過,返回django.contrib.auth.models.User實例,反之則是django.contrib.auth.models.AnonymousUser
.META/.session
這個本身注意一下
.method/.content_type
這種鬼東西,能夠忘記了。
RESTframework提供了一個標準的Response方法的類供調用。
Response(data, status=None, template_name=None, headers=None, content_type=None)
上面的調用一看就知道了,大概正常狀況下只須要一個data就能夠了,除非是刁鑽的自定義。那就本身玩去吧。
.data
響應的序列化的數據
.status_code
這是標準的HTTP請求返回的數字狀態碼,前端根據狀態碼判斷有沒有成功,好比你們熟悉的404.
.content/.template_name
瞭解但不是很重要的參數
Response的擴展
response = Response() response['Cache-Control'] = 'no-cache'
這種東西,一看就懂,就很少說了,能夠往reponse實例裏面添加額外的參數.
這裏主要介紹的是繼承Django views的擴展視圖類。
APIView
APIView跟正常的View類仍是有不少區別的
a、到達處理函數的請求將會是rest framework的請求實例,而不是Django的HttpResponse實例
b、此類的處理函數返回的是rest framework的Reponse對象,而不是HttpResponse對象。會自動管理內容協調。設置正確的響應渲染。
c、任何的API報錯都會被抓去協調到合適的響應裏面
d、即將到來的請求將會被認證,驗證權限,在運行到dispatch方法處理請求以前
使用APIView跟正常的View類很類似,即將到來的請求會被派遣到合適的處理函數方法上,好比.get()或者.post()。額外地,還有不少的屬性能夠被設置在類上控制API政策的不一樣方面。
APIView屬於很基礎的封裝高級視圖類了,因此這邊也就簡單粗暴的貼上官方的文檔裏面的示例。
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class ListUsers(APIView): """ 查看系統裏面全部的用戶 * 須要token驗證 * 只有admin用戶能夠訪問此視圖 """ authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser,) def get(self, request, format=None): """ 返回用戶列表 """ usernames = [user.username for user in User.objects.all()] return Response(usernames)
APIView裏面有不少方法,可是我的以爲沒什麼很重要的,這裏就都忽略了,不重要。下面簡單列一下,有用的標紅。
屬性:
.renderer_classes
.parse_classes
.authentication_classes
.throttle_classes
.permission_classes
.content_negotiation_class
方法:
.get_renderers(self)
.get_parsers(self)
.get_authenticators(self)
.get_throttles(self)
.get_permissions(self)
.get_content_negotiator(self)
.get_exception_handler(self)
下面的方法在dispatching處理方法以前被調用
.check_permissions(self.request)
.check_throttles(self.request)
.perform_content_negotiation(self, request, force=False)
Dispatch方法
用來分配.get(), .post(), .post(), patch()和.delete()方法上。
rest framework做爲一個功能強大的面向資源的框架,對於資源的處理,固然不可能限制於CBV,FBV下面也是能夠用的,只是在真正的作生產的時候你纔會發現,CBV寫起來有多方便,有多爽。
@api_view()
@api_view(http_method_names=['GET'])
如上面的小標題,此函數是一個裝飾器函數,看個簡單的示例,須要本身手動返回數據
from rest_framework.decorators import api_view @api_view() def hello_world(request): return Response({"message": "Hello, world!"})
這個view會使用默認的渲染,解析,認證類,除非你在設置裏面特殊標記了。
正常狀況下,get方法會被接受,其餘方法會拋出"405 Method Not Allowed",爲了防止,須要特別標明哪些方法此視圖容許
@api_view(['GET', 'POST']) def hello_world(request): if request.method == 'POST': return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "Hello, world!"})
API policy decorators
用來重寫默認的設置,rest framework提供了一系列能夠添加到視圖上的裝飾器,可是這些裝飾器必須在@api_view裝飾器以後。好比,如今作一個示例,對視圖進行節流,保證它對於特殊的用戶,天天只能被調用一次。使用@throttle_class裝飾器
from rest_framework.decorators import api_view, throttle_classes from rest_framework.throttling import UserRateThrottle class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) # 定義在@api_view以後 def view(request): return Response({"message": "Hello for today! See you tomorrow!"})
這些裝飾器對應的屬性設定在APIView的基類裏,能夠用的裝飾器:
@render_classes()
@parser_classes()
@authentication_classes()
@throttle_classes()
@permission_classes()
View schema decorator
重寫FBV的默認架構生成, 你可能須要用到@schema裝飾器,也須要寫在@api_view裝飾器後面
from rest_framework.decorators import api_view, schema from rest_framework.schemas import AutoSchema class CustomAutoSchema(AutoSchema): def get_link(self, path, method, base_url): # override view introspection here... @api_view(['GET']) @schema(CustomAutoSchema()) def view(request): return Response({"message": "Hello for today! See you tomorrow!"})
這個裝飾器須要一個AutoSchema實例、一個AutoSchema子類實例或MachemalSchema實例在Schemas文檔中如上所描述的。你能夠傳遞None爲了將視圖排除在架構生成以外
@api_view(['GET']) @schema(None) def view(request): return Response({"message": "Will not appear in schema!"})