1、View
1, class-based view of the Class-based Views
REST framework provides APIView is Django's View subclass
sent to View, Request request: is an instance of the Request class REST framework instead of Django HttpRequest class instance
View returned Response Response: Return REST framework of Response instead Django the HttpRequest
dispatches the request to a handler method before , may be performed as follows: authentication, proper permissions, and (or) a throttle check
View View
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 ListUser (APIView): "" " lists the system used in the user's view * Requires token authentication * Only an administrator user can access this view " "" # authentication_classes = [authentication.TokenAuthentication] # need to carry a token access permission_classes = [ permissions.IsAdminUser] DEF GET (Self, Request, the format = None): "" " . A List of the Return All Users " "" of usernames is = [user.username for User in User.objects.all ()] # 1: lowb # QuerySet User.objects.all = () # of usernames is = [] # for user in queryset: # usernames.append(user.username) return Response(usernames)
url
from django.urls import path from .views import ListUser, hello_world, view1, view2 urlpatterns = [ path('user-list', ListUser.as_view()), ]
2, API policy properties
The following controls which aspects API view pluggable.
3, API policy instance method
The following methods were used to instantiate API REST framework various pluggable policy. You usually do not need to override these methods.
4, API Implementation Strategy
Call the following method before dispatching to the handler method.
5, dispatch related methods
1、.initialize_request(self, request, args, *kwargs)
# Initialization REQUEST request, returns Request instance
2、.initial(self, request, args, *kwargs)
运行在调用方法处理程序之前,运行你需要的任何功能。可以执行权限认证,节流限制,内容协商
3、.handle_exception(self, exc)
处理程序方法抛出的任何异常都将传递给此方,通过返回适当的响应,或重新引发错误。
4、.finalize_response(self, request, response, args, *kwargs)
确保从处理程序方法返回的任何 Response
对象都被渲染成正确的内容类型
2、基于函数的视图 (Function Based Views)
说 [基于类的视图] 永远是最好的解决方案是一个错误
REST framework 还允许您使用常规的基于函数的视图
urls
from django.urls import path from .views import ListUser, hello_world, view1, view2 urlpatterns = [ path('user-list', ListUser.as_view()), # @api_view path('hello-world', hello_world), path('view1', view1), # 节流 path('view2', view2), # schema api概要描述 ]
1、@api_view()
语法:@api_view(http_method_names=['GET'])
from rest_framework.decorators import api_view @api_view(http_method_names=['GET', 'POST']) def hello_world(request): if request.method == 'POST': return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "hello world!"})
2、API 策略装饰器 (API policy decorators)
REST framework 提供了一系列可以添加到视图中的附加装饰器
例如,要创建一个使用限流来确保它每天只能由特定用户调用一次的视图,请使用 @throttle_classes
装饰器,传递一个限流类列表:
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 view1(request): return Response({"message": "hello for today!see you tomorrow"})
可用的装饰者有:
@renderer_classes(...)
@parser_classes(...)
@authentication_classes(...)
@throttle_classes(...)
@permission_classes(...)
3、视图模式装饰器 (View schema decorator)
要覆盖基于函数的视图的默认模式生成,您可以使用 @schema
装饰器
### # 视图模式装饰器 (View schema decorator) ### from rest_framework.schemas import AutoSchema from rest_framework.decorators import schema class CustomAutoSchema(AutoSchema): def get_link(self, path, mehod, base_url): # 这里重写视图,描述该API的概要 pass @api_view(http_method_names=['GET']) @schema(CustomAutoSchema) # @schema(None) def view2(request): return Response({"message": "hello for today! see you tomorrow!"})
3、总结
1、APIView源码