Django RateLimit 403页面未被取代

时间:2013-04-20 18:36:08

标签: python django rate-limiting ratelimit

我已经在我的项目上设置了django-ratelimit,它看起来工作正常,但是当访问者达到限制时我无法删除丑陋的403错误页面。我正试图取代它,正如他们在他们的文档中所说的那样:

  

有可选的中间件可以使用自定义视图来处理   限速例外。要使用它,请添加   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)

我做错了什么?

1 个答案:

答案 0 :(得分:3)

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

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

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