在 Django REST Framework (DRF) 中,装饰器(Decorators)通常用于视图函数或类视图,以控制访问权限、请求方法、认证等行为。以下是 DRF 中常用的装饰器及其功能说明:
1. @api_view
- 用途: 用于基于函数的视图,指定允许的 HTTP 请求方法(如 GET、POST、PUT 等)。
- 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import api_view from rest_framework.response import Response@api_view(['GET', 'POST']) def my_view(request):if request.method == 'GET':return Response({"message": "GET request"})elif request.method == 'POST':return Response({"message": "POST request"})
- 说明:
- 限定视图支持的 HTTP 方法。
- 自动处理
Request
对象和Response
对象的解析与返回。 - 默认情况下,视图会返回 405 状态码(Method Not Allowed)给不支持的请求方法。
2. @permission_classes
- 用途: 指定视图的权限要求,控制哪些用户可以访问该视图。
- 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated@api_view(['GET']) @permission_classes([IsAuthenticated]) def secure_view(request):return Response({"message": "This is a protected view"})
- 说明:
IsAuthenticated
要求用户已登录。- 可组合多个权限类,如
[IsAuthenticated, IsAdminUser]
。 - 常与
api_view
或类视图一起使用。
3. @authentication_classes
- 用途: 指定视图的认证方式,如 TokenAuthentication、SessionAuthentication 等。
- 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import api_view, authentication_classes from rest_framework.authentication import TokenAuthentication@api_view(['GET']) @authentication_classes([TokenAuthentication]) def token_protected_view(request):return Response({"message": "Token authenticated"})
- 说明:
- 定义认证机制,验证用户身份。
- 通常与
permission_classes
配合使用。
4. @throttle_classes
- 用途: 限制视图的请求频率,防止 API 滥用。
- 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import api_view, throttle_classes from rest_framework.throttling import UserRateThrottle@api_view(['GET']) @throttle_classes([UserRateThrottle]) def throttled_view(request):return Response({"message": "Throttled view"})
- 说明:
- 使用 DRF 的限流机制(如
AnonRateThrottle
、UserRateThrottle
)。 - 可通过配置文件自定义限流规则。
- 使用 DRF 的限流机制(如
5. @renderer_classes
- 用途: 指定视图的渲染方式,如 JSON、XML 等。
- 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer@api_view(['GET']) @renderer_classes([JSONRenderer]) def json_view(request):return Response({"message": "JSON response"})
- 说明:
- 控制 API 的响应格式。
- 默认使用 DRF 的全局渲染配置,但可通过此装饰器覆盖。
6. @parser_classes
- 用途: 指定视图可以解析的请求数据格式,如 JSON、Form 数据等。
- 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import api_view, parser_classes from rest_framework.parsers import JSONParser@api_view(['POST']) @parser_classes([JSONParser]) def json_parser_view(request):return Response({"received": request.data})
- 说明:
- 限制请求体的数据格式。
- 常用于特定场景,如只接受 JSON 数据。
7. @action (用于 ViewSet)
- 用途: 在
ViewSet
中定义自定义动作,扩展默认的 CRUD 操作。 - 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import action from rest_framework.viewsets import ViewSet from rest_framework.response import Responseclass MyViewSet(ViewSet):@action(detail=True, methods=['GET'])def custom_action(self, request, pk=None):return Response({"message": f"Custom action for {pk}"})
- 说明:
detail=True
表示针对单一资源(如/resource/{pk}/custom_action/
)。detail=False
表示针对资源集合(如/resource/custom_action/
)。- 可指定允许的 HTTP 方法。
8. @schema
- 用途: 自定义 API 文档的 schema,配合 DRF 的自动文档生成工具(如 drf-yasg 或 drf-spectacular)。
- 模块:
rest_framework.decorators
- 示例:
from rest_framework.decorators import api_view, schema from rest_framework.schemas import AutoSchema@api_view(['GET']) @schema(AutoSchema(manual_fields=[])) def documented_view(request):return Response({"message": "Documented view"})
- 说明:
- 用于自定义 OpenAPI 文档的元数据。
- 通常结合文档生成工具使用。
使用注意事项
- 装饰器顺序: 在基于函数的视图中,
@api_view
必须是最外层的装饰器,否则会报错。# 正确 @api_view(['GET']) @permission_classes([IsAuthenticated]) def my_view(request):pass# 错误 @permission_classes([IsAuthenticated]) @api_view(['GET']) def my_view(request):pass # 会抛出异常
- 类视图: 装饰器(如
@permission_classes
、@authentication_classes
)通常用于函数视图。对于类视图,推荐在类中设置属性(如permission_classes
、authentication_classes
)。from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticatedclass MyAPIView(APIView):permission_classes = [IsAuthenticated]def get(self, request):return Response({"message": "Class-based view"})
- 全局配置: 许多装饰器功能(如权限、认证、限流)可以通过 DRF 的全局设置(
REST_FRAMEWORK
)配置,减少重复代码。
总结
DRF 的装饰器为视图提供了灵活的控制方式,适用于权限、认证、限流、数据解析和渲染等场景。常用的装饰器包括 @api_view
、 @permission_classes
、 @authentication_classes
、 @throttle_classes
等。对于 ViewSet
,@action
是扩展自定义路由的利器。