[英]How to check object level permission efficiently in DRF?
Scenario: In DRF I had to write following lines of code to check permission for the user场景:在DRF中,我必须编写以下代码行来检查用户的权限
class RetrieveCampaignListView(APIView) :
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request , *args, **kwargs):
if request.user.has_perm('campaign.view_campaign'):
try:
#some view code
except:
return Response({"status":False}, status=status.HTTP_404_NOT_FOUND)
else:
return Response({"status":"Sorry User is not permitted"})
But I want to shorten the但我想缩短
request.user.has_perm('campaign.view_camapign') and it's else condition
into something like this.变成这样的东西。
@check_permission('campaign.view_campaign')
Any Help Would be highly appericiated.任何帮助都会受到高度重视。
You can use DRF custom permissions:您可以使用 DRF 自定义权限:
from rest_framework import permissions
class ViewCampaignPermission(permissions.BasePermission):
message = 'Sorry User is not permitted'
def has_permission(self, request, view):
return request.user.has_perm('campaign.view_campaign'):
class RetrieveCampaignListView(APIView) :
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated, ViewCampaignPermission]
...
See: https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions请参阅: https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions
or if you really want a decorator, you can use something like:或者如果你真的想要一个装饰器,你可以使用类似的东西:
from functools import wraps
from rest_framework.views import APIView
def has_permission(permission):
def has_permission_decorator(func):
@wraps(func)
def has_permission_wrapper(*args, **kwargs):
request = args[0].request
if not request.user.has_perm(permission):
return Response(status='Sorry User is not permitted'})
return func(*args, **kwargs)
return has_permission_wrapper
return has_permission_decorator
class RetrieveCampaignListView(APIView):
@has_permission('campaign.view_campaign')
def get(self, request, *args, **kwargs):
pass
But this will only work for one permission string.但这仅适用于一个权限字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.