我将DRF用于restapi,所以现在我对api应用了节流。为此,我创建了以下节流范围
用户速率限制
自动油门
紧急油门
perViewsThrottles(视情况而定)
目前我得到以下回复:
{"detail":"Request was throttled. Expected available in 32.0 seconds."}
我想要这样的回应:
{"message":"request limit exceeded","availableIn":"32.0 seconds","throttleType":"type"}
DRF文档中没有可供定制的内容。如何根据要求定制我的响应?在
为此,您可以实现一个custom exception handler function,在^{} 异常情况下返回自定义响应。在
然后,您需要将这个自定义异常处理程序添加到您的DRF设置中。在
^{pr2}$我认为如果不更改一些DRF代码,了解
throttleType
会有点困难,因为DRF会在任何Throttle类限制请求的情况下引发一个Throttled
异常。不会将任何信息传递给Throttled
异常,throttle_class
正在引发该异常。在我知道这是一个旧的线程,但是除了Rahul的答案之外,还有一种方法可以在消息中包含throttleType:
您首先需要重写Throttled异常类:
创建一个名为
rest_exceptions.py
的文件,并创建以下内容:这里为引发异常的throttle实例添加一个kwarg(如果提供)。您还可以重写详细信息消息的行为,并使用
wait
值执行您希望的操作。我决定不是连接细节并等待,而是使用原始细节消息。接下来,您需要创建一个自定义视图集,该视图集将调节器传递给受限制的异常。创建一个名为
rest_viewsets.py
的文件并创建以下内容:既然您有了一个将存储throttle实例的自定义异常,以及一个将实例传递给异常的视图集,那么下一步就是实现一个继承此视图集的视图,并使用您列出的throttle类之一。在您的
^{3美元views.py
中,在预期的视图下(因为您没有提供,所以我将其称为MyViewset
):此时,你的应用程序会像往常一样检查节流阀,但也会将也传递给throttle实例。我也把油门信息改写成你想要的。我们现在可以使用Rahul提供的解决方案,只需做一些修改。创建自定义异常处理程序:
此时您可以轻松地访问throttle类的任何其他属性,但您只需要类名。
最后,将处理程序添加到DRF设置中:
您可以通过重写视图的
throttled
方法来更改限制响应的消息。例如:相关问题 更多 >
编程相关推荐