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