如何将TokenAuthentication身份验证类添加到Django FBV

时间:2018-11-13 07:56:04

标签: django python-3.x django-rest-framework django-views

我知道如何在Django Rest Framework的CBV中创建令牌认证。参见下面的随机示例

class Something(viewsets.ModelViewSet):
    """Handles Creating, reading and updating Patients"""

    serializer_class = serializers.SomeSerializer
    queryset = Some_Model.objects.all()
    authentication_classes = (TokenAuthentication,)
    filter_backends = (filters.SearchFilter,)
    permission_classes = (IsAuthenticated,)

我想为我的FBV创建令牌认证。那可能吗。以下是我的看法。我的整个项目都在Django rest Framework上。只有以下函数会在常规django模板模板中呈现。我想在以下功能中添加令牌认证

@api_view(http_method_names=['GET'])
@authentication_classes((TokenAuthentication,))
def some_function(request, pk):
    #code below

1 个答案:

答案 0 :(得分:1)

特别感谢@JPG和@invincfully cool,否则,我无法在下面完成此操作

from rest_framework.decorators import authentication_classes
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import api_view
from rest_framework.decorators import permission_classes
from rest_framework.permissions import IsAuthenticated


@api_view(http_method_names=['GET'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def some_function(request, pk):
    #code below