如何从Django Rest Framework中的权限类访问API视图中的变量?

时间:2017-02-28 17:11:01

标签: python django django-rest-framework

所以我设置了这个系统,这样每当对我的API发出POST,PUT或DELETE请求时,我会检查标题中的商店密钥,然后匹配它。我试图使用权限类来设置它。我正在做以下事情:

permissions.py

SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')

class BasePermission(object):

    def has_permission(self, request, view):
        return True

    def has_object_permission(self, request, view, obj):
        return True

class IsShopkeeperClient(BasePermission):

    def has_permission(self, request, view):
        if request.method in SAFE_METHODS:
            return True
        else:
            if request.method == 'POST' or request.method == 'PUT' or request.method == 'DELETE':
                if not request.META.get('HTTP_SHOPKEY') == view.shop.key:
                    return False
                return True

请注意我是如何尝试在我的许可下致电view.shop.key的。在我看来,我正在做以下事情:

@api_view(['GET', 'POST'])
@permission_classes((IsShopkeeperClient,))
def categories_list(request, username):
    try:
        shop = Shop.objects.get(username=username)
        categories = shop.categories.all()
    except:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = CategorySerializer(categories, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CategorySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

所以,基本上,在我看来,商店是一个变量。结果,我收到以下错误:

  

' categories_list'对象没有属性' shop'

这些方面的东西。那么,我如何将商店传递给权限类并从那里访问它?有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

使用课程,可以轻松将商店设置为动态属性。

class CategoriesList(APIView):

    permission_classes = (IsShopkeeperClient,)

    @property
    def shop(self):
        if not hasattr(self, '_shop'):
            self._shop = Shop.objects.get(username=self.kwargs['username'])
        return self._shop

    def get(self, request, format=None):
        # add the get code here

    def post(self, request, format=None):
        # add the post code here

答案 1 :(得分:0)

类 IsShopkeeperClient(BasePermission):

def has_permission(self, request, view):
    if request.method in SAFE_METHODS:
        return True
    else:
        if request.method == 'POST' or request.method == 'PUT' or request.method == 'DELETE':
            shop = Shop.objects.get(username=view.kwargs.get('username'))
            if not request.META.get('HTTP_SHOPKEY') == shop.key:
                return False
            return True