簡體   English   中英

根據請求的類型,在API視圖的一部分上應用tokenauthentication Django rest框架

[英]Apply tokenauthentication Django rest framework on part of the API view based on the type of the request

我是Django休息框架的新手,並且正在努力使用api視圖令牌認證。 以下是我的代碼

@api_view(['POST'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))

    def create_user(request):
        """
        API to add user
        """
        if request.method == 'POST':
            request_body = request.data['users']
            created_user_ids = []
            # Data must be provided and validated
            validation = UserSerializer(data=request_body, many=True)
            validation.is_valid(raise_exception=True)
            created_user_ids.append(validation.save())

            return Response(
                data={'users': [{'id': user_id} for user_id in created_user_ids]},
                content_type='json',
                status=status.HTTP_201_CREATED
            )

我需要在視圖的一部分上應用tokenauthentication,而不是在整個視圖上。 身份驗證應基於請求的類型。 例如,如果type是POST,則不應該有任何身份驗證,但對於相同的視圖,如果請求以PUT,GET,PATCH等形式進入,則它應該對請求進行身份驗證。

如果我理解得很好,您希望將IsAuthenticated權限應用於您的視圖,除非該方法是POST

我建議創建一個自定義權限

class IsAuthenticatedOrPost(IsAuthenticated):
    def has_permission(self, request, view):
        if request.method == 'POST':
            return True
        return super().has_permission(request, view)

並使用類代替IsAuthenticated@permission_classes裝飾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM