[英]Apply tokenauthentication Django rest framework on part of the API view based on the type of the request
I am new to Django rest framework and struggling with api view token authentication. 我是Django休息框架的新手,并且正在努力使用api视图令牌认证。 Following is my code
以下是我的代码
@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
)
I need to apply tokenauthentication on part of the view not on whole view. 我需要在视图的一部分上应用tokenauthentication,而不是在整个视图上。 Authentication should be based over type of the request.
身份验证应基于请求的类型。 For example If type is POST there should not be any authentication but for the same view if request came in as PUT, GET, PATCH etc it should authenticate request.
例如,如果type是POST,则不应该有任何身份验证,但对于相同的视图,如果请求以PUT,GET,PATCH等形式进入,则它应该对请求进行身份验证。
If I understand well you want to apply IsAuthenticated
permission to your view except when the the method is a POST
. 如果我理解得很好,您希望将
IsAuthenticated
权限应用于您的视图,除非该方法是POST
。
I would suggest to create a Custom Permission : 我建议创建一个自定义权限 :
class IsAuthenticatedOrPost(IsAuthenticated):
def has_permission(self, request, view):
if request.method == 'POST':
return True
return super().has_permission(request, view)
And use that class instead of IsAuthenticated
in your @permission_classes
decorator. 并使用类代替
IsAuthenticated
在@permission_classes
装饰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.