2

我已经在我的项目上设置了 django-ratelimit,它似乎工作正常,除了当访问者达到他们的限制时我无法删除丑陋的 403 错误页面。正如他们在他们的文档中所说的那样,我正在尝试替换它,内容如下:

有一个可选的中间件可以使用自定义视图来处理 Ratelimited 异常。要使用它,请将 ratelimit.middleware.RatelimitMiddleware 添加到您的 MIDDLEWARE_CLASSES(靠近列表底部)并将 RATELIMIT_VIEW 设置为您要使用的视图的完整路径。

RATELIMIT_VIEW 中指定的视图将获得两个参数,请求对象(在 ratelimit 处理之后)和异常。

这是我的代码中的内容:

设置:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'ratelimit.middleware.RatelimitMiddleware',
)

RATELIMIT_VIEW = 'myapp.views.beenLimited'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'myapp',
    'ratelimit',
)

RATELIMIT_USE_CACHE = 'default'

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'ratelimit-tests',
    },
}

意见:

from ratelimit.decorators import ratelimit

@ratelimit(method='POST', block=True, rate='10/m')
def pullFromDatabase(request):
...

def beenLimited(request):
    message = "A few too many tries for today buddy. Please try again tomorrow."
    HttpResponse(message)

我究竟做错了什么?

4

1 回答 1

4

我不确定这是否有帮助,但尝试修复beeLimited视图以更正一个

def beenLimited(request, exception):
    message = "A few too many tries for today buddy. Please try again tomorrow."
    return HttpResponse(message)

另一种方法是检查视图中的request.limited属性pullFromDatabase。这将需要 set block=True

于 2013-04-20T19:08:49.977 回答