简体   繁体   English

如何应用限制只是为了在 DRF 视图集中创建操作?

[英]How to apply throttling just to create action in DRF viewsets?

I have a viewset and I want to apply throttling to only create action of that viewset and I don't want it to be applied to update , destroy , retrieve and etc...我有一个视图集,我想应用限制来仅create该视图集的操作,我不希望它应用于updatedestroyretrieve等...

class UserViewSet(viewsets.ModelViewSet):
    # should only be applied to the create action
    throttle_classes = [SomeThrottle] 
    ...

As described in Introspecting ViewSet actions [DRF docs] you can inspect the action attribute to set the throttle_classes based on the current action by overriding the get_throttles method:Introspecting ViewSet actions [DRF 文档]中所述,您可以检查action属性以通过覆盖get_throttles方法来根据当前操作设置throttle_classes

class UserViewSet(viewsets.ModelViewSet):
    def get_throttles(self):
        if self.action == 'create':
            throttle_classes = [SomeThrottle]
        else:
            throttle_classes = []  # No throttle for other actions
        return [throttle() for throttle in throttle_classes]

if use ScopedRateThrottle instead of Custom throttles如果使用ScopedRateThrottle而不是 Custom throttles

# settings

    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.ScopedRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'submit': '1/minute',
    }

class SomeViewSet(mixins.CreateModelMixin, GenericViewSet)
    ....

    def get_throttles(self):
        if self.action == 'create':
            self.throttle_scope = 'submit'
        return super().get_throttles()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM