首页 > 解决方案 > 如何自定义 django-ratelimit 403 禁止页面?

问题描述

我正在使用 django-ratelimit 2.0 来限制我的视图。我想为不同的视图显示不同的(自定义)403 禁止页面。例如,如果它是一个注册视图,它应该在 1 分钟内给出一条消息再试一次。如果是忘记密码视图,则应在 12 小时后重试消息。基本上我想要不同视图的不同速率限制消息。

标签: pythondjangoweb-frameworksweb-site-project

解决方案


这将帮助你 https://django-ratelimit.readthedocs.io/en/stable/usage.html#ratelimit.exceptions.Ratelimited

设置.py

DEBUG = False

ALLOWED_HOSTS = ['*']

视图.py

from django.shortcuts import render
from django.http import HttpResponse
from ratelimit.decorators import ratelimit  # 进行请求限制
from ratelimit.exceptions import Ratelimited  # 进行请求限制,判断403
# Create your views here.


@ratelimit(key='ip', rate='2/m',block=True)
def Hello(request):
    return render(request, 'hello.html')


def handler403(request, exception=None):
    if isinstance(exception, Ratelimited):
        return HttpResponse('Sorry you are blocked', status=429)
    return HttpResponse('Forbidden')

网址.py

handler403 = views.handler403

推荐阅读