質問

I have setup django-ratelimit on my project and it appears to be working fine except that I can't get the ugly 403 error page removed when a visitor reaches their limit. I am trying to replace it as they say in their docs, which read:

There is optional middleware to use a custom view to handle Ratelimited exceptions. To use it, add ratelimit.middleware.RatelimitMiddleware to your MIDDLEWARE_CLASSES (toward the bottom of the list) and set RATELIMIT_VIEW to the full path of a view you want to use.

The view specified in RATELIMIT_VIEW will get two arguments, the request object (after ratelimit processing) and the exception.

Here is what I have in my code:

SETTINGS:

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',
    },
}

VIEWS:

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)

What am I doing wrong?

役に立ちましたか?

解決

I am not sure whether this help but try to fix beeLimited view to correct one

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

Another approach is check request.limited attribute in pullFromDatabase view. It will require set block=True.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top