經過看源碼能夠發現 APIView 直接繼承了 Django View 這個基類,在此基礎上添加了 render_classes, parser_classes, authentication_classes 等等,因而可知 APIView 仍是比較偏底層的, 但經過使用它能夠相對靈活實現一些自定義功能。
介紹APIView: https://www.django-rest-framework.org/api-guide/views/html
APIView 類與 Django原生View 有如下區別:django
在使用上 APIView 類與 View 幾乎相差不大。收到的客戶端請求會被分發到相關的 handler 方法如:.get(), .post()。因爲不一樣 API 的 policy 的不一樣,APIView 中設置了相應的屬性。json
下面編寫一個簡單的 view.py with APIView
參照: https://www.django-rest-framework.org/tutorial/3-class-based-views/api
1 from products.models import Product 2 from products.serializers import ProductSerializer 3 from django.http import Http404 4 from rest_framework.views import APIView 5 from rest_framework.response import Response 6 from rest_framework import status 7 8 9 class ProductListView(APIView): 10 """ 11 List all products 12 """ 13 def get(self, request, format=None): 14 products = Product.objects.all() 15 products_serializer = ProductSerializer(products, many=True) # 序列化 products 對象成 json 格式;many 表示返回多條數據 16 return Response(products_serializer.data) 17 18 def post(self, request, format=None): 19 serializer = ProductSerializer(data=request.data) 20 if serializer.is_valid(): 21 serializer.save() # call serializer "create" method 22 return Response(serializer.data, status=status.HTTP_201_CREATED) 23 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
注: ProductSerializer 實現見以前的文章 (https://www.cnblogs.com/crazy-chinese/p/9828095.html)ide