REST框架提供了一個APIView類,它是Django View類的子類。
APIView類View通過以下方式與常規類不同:
傳遞給處理程序方法的請求將是REST框架的Request實例,而不是Django的HttpRequest實例。
處理程序方法可能會返回REST框架Response,而不是Django HttpResponse。該視圖將管理內容協商並在響應上設置正確的渲染器。
任何APIException例外都將被捕獲並調解爲適當的響應。
將傳入的請求進行身份驗證,並在將請求分派給處理程序方法之前運行適當的權限和/或限制檢查。
使用APIView該類與使用常規View類幾乎相同,像往常一樣,傳入的請求被分派到適當的處理程序方法,如.get()或.post()。另外,可以在控制API策略的各個方面的類上設置許多屬性。
例如:
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):
"""
View to list all users in the system.
* Requires token authentication.
* Only admin users are able to access this view.
"""
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAdminUser,)
def get(self, request, format=None):
"""
Return a list of all users.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
更多django rest framework的知識請參考下面一篇文檔,寫的比較詳細
https://www.cnblogs.com/derek1184405959/p/8733194.html(轉)