一、warp view的两种方式
(1) FBV:function based view
(2) CBV:class based view
二、FBV方式简要介绍
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']) #特点一:@api_view 修饰,如果学过JAVA应该会很熟悉,JAVA中的注释法 @controller这样的类型
def snippet_list(request): #接受的是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)
URL定位描述方式:
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>', views.snippet_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns) # 使资源没有后缀限制,maybe
三、CBV 方式简要介绍
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class SnippetList(APIView): #APIView ,its important # 特点一、class 包装 view
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None): # 特点二、get ,post,put等方式通过def 实现
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
def post(self, request, format=None):
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)
URL定位描述方式:
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.SnippetList.as_view()), # as_view
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
四、CBV 深入了解
4.1 APIView 与 View的不同
(1) request 不同: APIView使Request的实例, View是HttpRequest的实例
(2) response 不同: Response和 HttpResponse之间的差别
(3) 任何APIException 都会被捕捉
(4) Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
和View一样,APIview的使用上只有两个比较大的区别,一、比较明确的区分get,post,put这样的请求的方式;二、一些不同的数据可以附加在类中,以实现不同的API policy
4.2 API policy
在了解API policy 之前,先了解如下内容,settings中有这些defaults such as:
DEFAULT_RENDERER_CLASSES: # use what renderers when return a response obj
Default:[
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
]
DEFAULT_PARSER_CLASSES # the set of parses when accessing the request.data
Default:[
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
]
DEFAULT_AUTHENTICATION_CLASSES # determines the default set of authenticators used when accessing the request.user
or request.auth
properties
Default:[
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
]
DEFAULT_PERMISSION_CLASSES #determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.
Defalut:[
'rest_framework.permissions.AllowAny',
]
DEFAULT_THROTTLE_CLASSES # determines the default set of throttles checked at the start of a view.
Defalut:[
]
.etc
4.3 CVB and API policy (attr ------------> function)
control the pluggable aspects of API views. The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
.render_classes .get_renderers(self)
.parser_classes .get_parsers(self)
.authentication_classes .get_authenticators(self)
.throttle_classes .get_throttles(self)
.permission_classes .get_permissions(self)
.content_negotiation_classed .get_content_negotiator(self)
4.4 FVB and API policy (通过修饰器进行描述)
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])
def view(request):
return Response({"message": "Hello for today! See you tomorrow!"})
@renderer_classes(...)
@parser_classes(...)
@authentication_classes(...)
@throttle_classes(...)
@permission_classes(...)