Skip to main content
 首页 » 编程设计

python之Django RateLimit 403 页面未被替换

2024年08月29日32Free-Thinker

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

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.

这是我的代码:

设置:

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) 

我做错了什么?

请您参考如下方法:

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

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

另一种方法是检查 pullFromDatabase View 中的 request.limited 属性。它需要设置 block=True。