首页 > 解决方案 > 我必须在我的 django 类视图中包含 authentication_classes 属性

问题描述

根据 Django Rest Framework,当您想指定要使用的身份验证时,您可以在设置文件中将其设置为全局,例如

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

或按班级查看,例如

@authentication_classes((SessionAuthentication, TokenAuthentication))

现在我似乎没有得到的是,当我们在设置中将其指定为全局时,我们是否还必须将其作为每个类视图包含在内。

这是我的班级视图的代码

from django.http import HttpResponse
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
# Create your views here.


@api_view(['GET'])
@authentication_classes((SessionAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def index_view(request, format=None):
    return Response([str(request.auth), str(request.user.password), str(request.session.username)])

这是我的 settings.py 文件中的代码

休息框架

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated'
    )
}

请我希望我足够具体

标签: pythondjangodjango-rest-framework

解决方案


推荐阅读