@api_view
是 Django REST Framework (DRF) 提供的一个装饰器,用于将常规 Django 视图函数转换为 API 视图。它允许你明确指定视图支持的 HTTP 方法(如 GET、POST 等)。
当你在视图中添加 @api_view
装饰器后出现 403 Forbidden 错误,通常有以下几种可能原因:
@api_view
装饰器未正确配置或与其他装饰器冲突原因:当使用 @api_view
并启用了会话认证时,DRF 仍会检查 CSRF token。
解决方案:
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import AllowAll
@api_view(['GET'])
@authentication_classes([SessionAuthentication])
@permission_classes([AllowAll])
def my_view(request):
# 你的视图逻辑
或者完全禁用 CSRF(仅适用于 API 端点):
from rest_framework.decorators import api_view
from rest_framework import exceptions
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # 禁用 CSRF 检查
@api_view(['GET'])
@authentication_classes([CsrfExemptSessionAuthentication])
def my_view(request):
# 你的视图逻辑
原因:DRF 默认设置了权限类,可能需要明确设置。
解决方案:
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
# 如果需要认证
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def authenticated_view(request):
# 需要认证的视图逻辑
# 如果允许匿名访问
@api_view(['GET'])
@permission_classes([AllowAny])
def public_view(request):
# 公开访问的视图逻辑
原因:装饰器顺序不正确可能导致问题。
正确顺序示例:
@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def my_view(request):
# 视图逻辑
原因:API 请求可能缺少必要的请求头。
解决方案: 确保请求包含正确的 Content-Type,例如:
Content-Type: application/json
对于需要认证的 API,还需要提供认证头:
Authorization: Token <your_token>
@api_view
通常用于:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
通过以上方法,你应该能够解决因添加 @api_view
导致的 403 错误问题。
没有搜到相关的文章