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.