检查Django REST Fram中相关对象的权限

2024-09-19 23:37:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了以下模型

class Flight(models.Model):
    ...

class FlightUpdate(models.Model):
    flight = models.ForeignKey('Flight', related_name='updates')
    ...

以及以下在REST框架扩展中使用NestedViewsetMixin的视图集

^{pr2}$

因此,要访问与Flight关联的FlightUpdates,URL是/flights/1/updates/。在

我想确保只有当人们有权更改与FlightUpdate关联的Flight对象时,才能创建FlightUpdates。在

在添加FlightUpdate时,如何执行额外的检查?如果我没试着用最好的方式来添加。在

if not request.user.has_perm('flights.change_flight', flight):
    raise PermissionError()

注意:我使用django-rules实现对象级权限。在


Tags: 对象name模型model定义modelsclassflight
1条回答
网友
1楼 · 发布于 2024-09-19 23:37:51

我通过实现一个自定义权限类来解决这个问题。在

from django.core.exceptions import ObjectDoesNotExist

from rest_framework.permissions import BasePermission, SAFE_METHODS

from .models import Flight


class FlightPermission(BasePermission):

    def has_permission(self, request, view):
        if request.method in SAFE_METHODS:
            return True

        try:
            flight = Flight.objects.get(pk=view.kwargs['parent_lookup_flight'])
        except ObjectDoesNotExist:
            return False

        return request.user.has_perm('flights.change_flight', flight)

相关问题 更多 >