Django's class-based views are a welcome departure from the old-style views.
REST framework provides anAPIViewclass, which subclasses Django'sViewclass.
REST框架提供了一个apiview类,这类是Django视图类。
APIViewclasses are different from regularViewclasses in the following ways:
APIView类不同于普通视图类在以下方面:
Requests passed to the handler methods will be REST framework'sRequestinstances, not Django'sHttpRequestinstances.
通过对处理方法要求将REST框架的要求的情况下,不是Django的HttpRequest实例。
Handler methods may return REST framework'sResponse, instead of Django'sHttpResponse. The view will manage content negotiation and setting the correct renderer on the response.
Handler方法可以返回REST框架的响应,而不是Django的HttpResponse。视图将管理内容协商和响应设置正确的渲染器。
AnyAPIExceptionexceptions will be caught and mediated into appropriate responses.
任何APIException异常将被介导的适当的反应。
Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
传入的请求在运行之前将被验证,并将适当的权限或节流检查后发送到处理程序的方法。
Using theAPIViewclass is pretty much the same as using a regularViewclass, as usual, the incoming request is dispatched to an appropriate handler method such as.get()or.post(). Additionally, a number of attributes may be set on the class that control various aspects of the API policy.
使用APIView类是相当经常使用的视图类,传入的请求被分派到一个合适的处理方法,例如.get()or.post()。此外,可以在控制API策略的各个方面的类上设置若干属性。
For example:
fromrest_framework.viewsimportAPIViewfromrest_framework.responseimportResponsefromrest_frameworkimportauthentication,permissionsclassListUsers(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,)defget(self,request,format=None):"""
Return a list of all users.
"""usernames=[user.usernameforuserinUser.objects.all()]returnResponse(usernames)
The following attributes control the pluggable aspects of API views.
下列属性控制API视图的可插入方面。
API policy instantiation methods
The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
API policy implementation methods
The following methods are called before dispatching to the handler method.
在分发给处理程序方法之前调用以下方法。
.check_permissions(self, request)
.check_throttles(self, request)
.perform_content_negotiation(self, request, force=False)
The following methods are called directly by the view's.dispatch()method. These perform any actions that need to occur before or after calling the handler methods such as.get(),.post(),put(),patch()and.delete().
以下的方法是由视图中直接调用。dispatch()方法。这些执行任何操作,需要发生之前或调用处理方法之后,例如.get(),.post(),put(),patch()
.initial(self, request, *args, **kwargs)
Performs any actions that need to occur before the handler method gets called. This method is used to enforce permissions and throttling, and perform content negotiation.
在处理方法调用之前执行任何需要发生的操作。此方法用于强制权限和节流,并执行内容协商。
You won't typically need to override this method.
Any exception thrown by the handler method will be passed to this method, which either returns aResponseinstance, or re-raises the exception.
处理方法抛出的任何异常都将传递给该方法,该方法返回响应实例,或重新引发异常。
The default implementation handles any subclass ofrest_framework.exceptions.APIException, as well as Django'sHttp404andPermissionDeniedexceptions, and returns an appropriate error response.
默认的实现处理的任何子类rest_framework.exceptions.apiexception,像Django的Http404和PermissionDenied例外,并返回适当的错误响应。
If you need to customize the error responses your API returns you should subclass this method.
如果需要自定义API返回的错误响应,则应将该方法的子类化为子类。
.initialize_request(self, request, *args, **kwargs)
Ensures that the request object that is passed to the handler method is an instance ofRequest, rather than the usual DjangoHttpRequest.
确保传递给处理程序方法的请求对象是请求的一个实例,而不是通常的HttpRequest。
You won't typically need to override this method.
.finalize_response(self, request, response, *args, **kwargs)
Ensures that anyResponseobject returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.
确保从处理程序方法返回的任何响应对象将被呈现为正确的内容类型,由内容协商确定。
You won't typically need to override this method.
Saying [that class-based views] is always the superior solution is a mistake.
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance ofRequest(rather than the usual DjangoHttpRequest) and allows them to return aResponse(instead of a DjangoHttpResponse), and allow you to configure how the request is processed.
REST框架允许您使用基于正则函数的视图。它提供了一套简单的装饰,把你的功能观确保他们接受请求的实例(而不是通常的Django HttpRequest)并允许他们返回响应(而不是一个Django HttpResponse),并允许您配置如何处理请求。
Signature:@api_view(http_method_names=['GET'], exclude_from_schema=False)
The core of this functionality is theapi_viewdecorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
此功能的核心是api_view装饰,以一个列表的HTTP方法视图应该回应。例如,您将如何编写一个非常简单的视图,该视图只手动返回一些数据:
fromrest_framework.decoratorsimportapi_view@api_view()defhello_world(request):returnResponse({"message":"Hello, world!"})
This view will use the default renderers, parsers, authentication classes etc specified in thesettings.
这种视图将使用默认的renderers, parsers, authentication等类的设置指定
By default onlyGETmethods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
这种默认只适用于GET方法,其他方法将返回"405 Method Not Allowed",若要更改此行为,请指定视图允许的方法,例如:
@api_view(['GET','POST'])defhello_world(request):ifrequest.method=='POST':returnResponse({"message":"Got some data!","data":request.data})returnResponse({"message":"Hello, world!"})
You can also mark an API view as being omitted from anyauto-generated schema, using theexclude_from_schemaargument.:
你也可以标记一个API视图是从任何自动生成的架构略,使用exclude_from_schema。
@api_view(['GET'],exclude_from_schema=True)defapi_docs(request):...
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must comeafter(below) the@api_viewdecorator. For example, to create a view that uses athrottleto ensure it can only be called once per day by a particular user, use the@throttle_classesdecorator, passing a list of throttle classes:
为了覆盖默认设置,REST框架提供了一套额外的装饰可以被添加到你视图里。这些必须经过@api_view装饰。例如,创建一个视图,使用油门确保它只能由特定用户每天一次,使用@throttle_classes装饰,通过节流阀类的列表:
fromrest_framework.decoratorsimportapi_view,throttle_classesfromrest_framework.throttlingimportUserRateThrottleclassOncePerDayUserThrottle(UserRateThrottle):rate='1/day'@api_view(['GET'])@throttle_classes([OncePerDayUserThrottle])defview(request):returnResponse({"message":"Hello for today! See you tomorrow!"})
These decorators correspond to the attributes set onAPIViewsubclasses, described above.
The available decorators are:
@renderer_classes(...)
@parser_classes(...)
@authentication_classes(...)
@throttle_classes(...)
@permission_classes(...)
Each of these decorators takes a single argument which must be a list or tuple of classes.