Views

Class-based Views

REST框架提供了一個(gè)APIView類,它是Django中View類的子類。
APIView 類和常規(guī)的View類有以下幾個(gè)方面的不同:

  • 傳遞給處理程序方法的請求將是REST框架的請求實(shí)例,而不是Django的HttpRequest實(shí)例。
  • 處理方法返回的是REST框架的Response而不是Django的HttpResponse。該視圖管理content negotiation,并根據(jù)響應(yīng)設(shè)置正確的渲染器。
  • 任何APIException異常將被捕獲并被調(diào)解為適當(dāng)?shù)捻憫?yīng)。
  • 傳入請求將被認(rèn)證,并且在將請求發(fā)送給處理程序方法之前,將運(yùn)行適當(dāng)?shù)臋?quán)限 and/or throttle 檢查。

使用APIView類與使用常規(guī)的View類一樣,像往常一樣,傳入的請求會調(diào)度適當(dāng)?shù)奶幚沓绦蚍椒ǎ?get()或.post()。 另外,可以在控制API策略的各個(gè)方面的類上設(shè)置許多屬性。
例如:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions

class ListUsers(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,)

    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames)

API policy attributes

以下屬性控制API視圖的可插入方面。

.renderer_classes
.parser_classes
.authentication_classes
.throttle_classes
.permission_classes
.content_negotiation_class

API policy instantiation methods

REST框架使用以下方法實(shí)例化各種可插拔API策略。 通常不需要重寫這些方法。

.get_renderers(self)
.get_parsers(self)
.get_authenticators(self)
.get_throttles(self)
.get_permissions(self)
.get_content_negotiator(self)
.get_exception_handler(self)

API policy implementation methods

調(diào)度處理程序方法之前調(diào)用以下方法。

.check_permissions(self, request)
.check_throttles(self, request)
.perform_content_negotiation(self, request, force=False)

Dispatch methods

以下方法直接由視圖的.dispatch()方法調(diào)用。 這些執(zhí)行任何需要在調(diào)用諸如.get(),.post(),put(),patch()和.delete()之類的處理程序方法之前或之后發(fā)生的任何操作。

.initial(self,request,* args,** kwargs)

執(zhí)行在調(diào)用處理程序方法之前需要執(zhí)行的任何操作。此方法用于執(zhí)行權(quán)限和限制,并執(zhí)行 content negotiation。通常不需要覆蓋此方法。

.handle_exception(self,exc)

處理程序方法拋出的任何異常都將傳遞給此方法,該方法返回一個(gè)響應(yīng)實(shí)例,或重新引發(fā)異常。
默認(rèn)實(shí)現(xiàn)處理rest_framework.exceptions.APIException的任何子類,以及Django的Http404和PermissionDenied異常,并返回適當(dāng)?shù)腻e(cuò)誤響應(yīng)。
如果您需要自定義您的API返回的錯(cuò)誤響應(yīng),則應(yīng)該對此方法進(jìn)行子類化。

.initialize_request(self,request,* args,** kwargs)

確保傳遞給handler方法的請求對象是Request的一個(gè)實(shí)例,而不是通常的Django HttpRequest。
通常不需要覆蓋此方法。

.finalize_response(self,request,response,* args,** kwargs)

確保從處理程序方法返回的任何Response對象將被渲染為content negotiation確定的正確內(nèi)容類型。
通常不需要覆蓋此方法。

Function Based Views

REST框架還允許你使用基于函數(shù)的常規(guī)視圖。 它提供了一組簡單的裝飾器,用于包裝基于函數(shù)的視圖,以確保它們接收到Request(而不是通常的Django HttpRequest)的實(shí)例,并允許它們返回一個(gè)Response(而不是Django HttpResponse),并允許你配置請求如何被處理。

@api_view()

Signature: @api_view(http_method_names=['GET'], exclude_from_schema=False)
這個(gè)功能的核心是api_view裝飾器,它包含你的視圖應(yīng)該響應(yīng)的HTTP方法的列表。 例如,這是你如何編寫一個(gè)非常簡單的視圖,只需手動返回一些數(shù)據(jù):

from rest_framework.decorators import api_view

@api_view()
def hello_world(request):
    return Response({"message": "Hello, world!"})

此視圖將使用settings中指定的默認(rèn)渲染器,解析器,驗(yàn)證類等。

默認(rèn)情況下只接受GET方法。 其他方法將以“405 Method Not Allowed”作為響應(yīng)。 要更改此行為,請指定視圖允許的方法,如下所示:

@api_view(['GET', 'POST'])
def hello_world(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"message": "Hello, world!"})

你還可以使用exclude_from_schema參數(shù)將API視圖標(biāo)記為從任何auto-generated schema中省略:

@api_view(['GET'], exclude_from_schema=True)
def api_docs(request):
    ...

API policy decorators

要覆蓋默認(rèn)settings,REST框架提供了一組可以添加到您的視圖中的其他裝飾器。 這些必須在(以下)@api_view裝飾器之后。 例如,要創(chuàng)建一個(gè)使用 throttle 確保每天只能由特定用戶調(diào)用一次的視圖,請使用@throttle_classes裝飾器,傳遞throttle類列表:

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!"})

這些裝飾器對應(yīng)于上面描述的APIView子類上設(shè)置的屬性。
可用的裝飾有:

  • @renderer_classes(...)
  • @parser_classes(...)
  • @authentication_classes(...)
  • @throttle_classes(...)
  • @permission_classes(...)

這些裝飾器中的每一個(gè)都采用一個(gè)參數(shù),它必須是列表或元組元素。

View schema decorator

要覆蓋基于函數(shù)的視圖的默認(rèn)模式生成,您可以使用@schema修飾器。這必須在@api_view裝飾器之后(下方)。例如:

from rest_framework.decorators import api_view, schema
from rest_framework.schemas import AutoSchema

class CustomAutoSchema(AutoSchema):
    def get_link(self, path, method, base_url):
        # override view introspection here...

@api_view(['GET'])
@schema(CustomAutoSchema())
def view(request):
    return Response({"message": "Hello for today! See you tomorrow!"})

該裝飾器將采用一個(gè)AutoSchema實(shí)例,一個(gè)AutoSchema子類實(shí)例或ManualSchema實(shí)例,如架構(gòu)文檔中所述。您可能會傳遞None以排除模式生成中的視圖。

@api_view(['GET'])
@schema(None)
def view(request):
    return Response({"message": "Will not appear in schema!"})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Class-based Views Django's class-based views are a welcom...
    陽光小鎮(zhèn)少爺閱讀 615評論 0 1
  • Class-based views 官方推薦使用通用視圖類 簡單示例# models.pyfrom django....
    wangfp閱讀 400評論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • Django: csrf防御機(jī)制 csrf攻擊過程 1.用戶C打開瀏覽器,訪問受信任網(wǎng)站A,輸入用戶名和密碼請求登...
    lijun_m閱讀 1,151評論 0 0
  • URLconf url()url()正則表達(dá)式中的參數(shù)既可以是位置參數(shù),也可以是關(guān)鍵字參數(shù)# 位置參數(shù),/arti...
    wangfp閱讀 295評論 0 0

友情鏈接更多精彩內(nèi)容