11

PUT并且PATCH都是同一个mixin(UpdateModelMixin)的一部分。

所以如果我像这样扩展它:

class UserViewSet(mixins.UpdateModelMixin, GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

两者PUTPATCH允许。我想根本不允许PUT我的应用程序(因为PATCH已经完成了工作,并且我想使用 just 来限制对象创建POST)。一种方法是创建权限:

class NoPut(permissions.BasePermission):
    """
    PUT not allowed.
    """
    message = 'You do not have permission to complete the action you are trying to perform.'

    def has_object_permission(self, request, view, obj):
        if view.action == "update":
            return False
        return True

并将此权限授予我所有允许PATCH. 这是最好的方法吗?有没有更优选的方式?

编辑:查看@wim提供的答案后,这是否是一个很好的解决方案(除了put删除映射之外,一切都保持不变):

from rest_framework.routers import SimpleRouter
class NoPutRouter(SimpleRouter):

    routes = [
        # List route.
        Route(
            url=r'^{prefix}{trailing_slash}$',
            mapping={
                'get': 'list',
                'post': 'create'
            },
            name='{basename}-list',
            initkwargs={'suffix': 'List'}
        ),
        # Dynamically generated list routes.
        # Generated using @list_route decorator
        # on methods of the viewset.
        DynamicListRoute(
            url=r'^{prefix}/{methodname}{trailing_slash}$',
            name='{basename}-{methodnamehyphen}',
            initkwargs={}
        ),
        # Detail route.
        Route(
            url=r'^{prefix}/{lookup}{trailing_slash}$',
            mapping={
                'get': 'retrieve',
                 # put removed
                'patch': 'partial_update',
                'delete': 'destroy'
            },
            name='{basename}-detail',
            initkwargs={'suffix': 'Instance'}
        ),
        # Dynamically generated detail routes.
        # Generated using @detail_route decorator on methods of the viewset.
        DynamicDetailRoute(
            url=r'^{prefix}/{lookup}/{methodname}{trailing_slash}$',
            name='{basename}-{methodnamehyphen}',
            initkwargs={}
        ),
    ]

还是我需要重新定义其他方法SimpleRoute(例如__init()__, get_routes(),_get_dynamic_routes()get_method_map())以使其正常工作?

4

7 回答 7

6

而不是mixins.UpdateModelMixin只使用定义你自己的 mixin 来执行补丁:

class UpdateModelMixin(object):
    """
    Update a model instance.
    """
    def partial_update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)

    def perform_update(self, serializer):
        serializer.save()
于 2017-04-21T05:45:05.130 回答
2

如果你想使用 builtin mixins.UpdateModelMixin,限制PATCH并禁止 swagger 显示 PUT 你可以使用http_method_names

class UserViewSet(mixins.UpdateModelMixin, GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    http_method_names = ["patch"]
于 2021-02-19T08:14:41.187 回答
1

我认为一个更好的解决方案是使用自定义路由器并禁用 PUT 路由。然后将您的自定义路由器用于视图集。

class SimpleRouter(BaseRouter):
    routes = [
        # List route.
        Route(
            url=r'^{prefix}{trailing_slash}$',
            mapping={
                'get': 'list',
                'post': 'create'
            },
            name='{basename}-list',
            initkwargs={'suffix': 'List'}
        ),
        # Dynamically generated list routes.
        # Generated using @list_route decorator
        # on methods of the viewset.
        DynamicListRoute(
            url=r'^{prefix}/{methodname}{trailing_slash}$',
            name='{basename}-{methodnamehyphen}',
            initkwargs={}
        ),
        # Detail route.
        Route(
            url=r'^{prefix}/{lookup}{trailing_slash}$',
            mapping={
                'get': 'retrieve',
                'put': 'update',
                'patch': 'partial_update',
                'delete': 'destroy'
            },
            name='{basename}-detail',
            initkwargs={'suffix': 'Instance'}
        ),
        # Dynamically generated detail routes.
        # Generated using @detail_route decorator on methods of the viewset.
        DynamicDetailRoute(
            url=r'^{prefix}/{lookup}/{methodname}{trailing_slash}$',
            name='{basename}-{methodnamehyphen}',
            initkwargs={}
        ),
    ]

^ 路由器实现看起来像这样。所以你只需要继承SimpleRouter, 或者可能DefaultRouter, 并定义routes你想要的类属性。您可以完全删除“放置”的映射Route(mapping={...}),或者您可以定义自己的操作来处理它并返回适当的 400-something resonse。

于 2017-04-20T21:04:23.293 回答
1

类似于@EbramShehata 的解决方案,但适用于drf-spectacular(OpenAPI 3)。这将不允许完全更新 (PUT) 并从生成的 OpenAPI 3 模式中排除它。

class SomeViewSet(
    mixins.UpdateModelMixin,
    ...
):
    @extend_schema(exclude=True)
    def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
        """Disallow full update (PUT) and allow partial update (PATCH)."""
        if kwargs.get("partial", False):  # Use .get() instead of .pop()
            return super().update(request, args, kwargs)

        raise MethodNotAllowed(request.method)
于 2021-10-20T14:36:32.060 回答
1

一个简单直接的方法:

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    http_method_names = ['get', 'post', 'patch'] # <---------

这样的PUT方法将不允许。

于 2021-10-27T02:03:28.507 回答
1

类似于@linovia 的答案,但使用标准的mixin:

from rest_framework.exceptions import MethodNotAllowed

class UpdateModelMixin(mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """
    update:
        Update Model
    """

    def update(self, *args, **kwargs):
        raise MethodNotAllowed("POST", detail="Use PATCH")

    def partial_update(self, request, *args, **kwargs):
        # Override Partial Update Code if desired
        return super().update(*args, **kwargs, partial=True)
于 2020-03-26T21:38:09.367 回答
1

这是我正在使用的解决方案:

class SomeViewSet(
    mixins.UpdateModelMixin,
    ...
):
    @swagger_auto_schema(auto_schema=None)
    def update(self, request, *args, **kwargs):
        """Disabled full update functionality"""
        partial = kwargs.get('partial', False)  # This must be .get() not .pop()
        if not partial:
            raise exceptions.MethodNotAllowed(request.method)

        return super(SomeViewSet, self).update(request, *args, **kwargs)

这也将在 drf-yasg UI 中禁用它。

于 2021-05-01T17:19:27.780 回答