Using Django Cache Middleware causes contrib.auth

2020-07-27 03:58发布

Problem: When I add UpdateCacheMiddleware and FetchFromCacheMiddleware to my Django project, I get unittest failures. This is regardless of the CACHE_BACKEND I use (right now I am using locmem://, but the errors are the same when I use file:///path_to_cache)

My Middleware:

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
)

All my test failures look like the one below: 'NoneType' object is unsubscriptable

======================================================================
Error: test_last_login (django.contrib.auth.tests.remote_user.RemoteUserTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Python26\lib\site-packages\django\contrib\auth\tests\remote_user.py",
 line 87, in test_last_login
    self.assertNotEqual(default_login, response.context['user'].last_login)
TypeError: 'NoneType' object is unsubscriptable

I must be missing something (or doing something wrong) as I have searched around the web for this issue, but no one seems to have encountered it.

Steps to Reproduce:

  1. Start a new django project (django-admin.py startproject myproject) and configure settings.py
  2. Add CACHE_BACKEND to settings.py and add the two Cache Middlewares from Django
  3. Run python manage.py test

Notes: There is only one test failure when using dummy:// cache and it is documented at: http://code.djangoproject.com/ticket/11640

1条回答
家丑人穷心不美
2楼-- · 2020-07-27 04:49

The solution to the failing tests is to set CACHE_MIDDLEWARE_SECONDS to 0 (e.g. set this to be 0 in your dev environment). This will allow the django.contrib tests to all pass.

查看更多
登录 后发表回答