cache_page in Django 1.8 导致 'str' object does not support item assignment 错误

cache_page in Django 1.8 causes 'str' object does not support item assignment error

我已经为 Django 的 cache_page 装饰器编写了一个包装器,以便可以将测试函数传递给它。据此,例如只有未经身份验证的用户才能看到缓存版本。这是包装器的代码:

from functools import wraps
from django.views.decorators.cache import cache_page
from django.utils.decorators import available_attrs
def passes_test_cache(test_func, timeout=None, using=None, key_prefix=None):
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request):
                return cache_page(timeout, cache=using, key_prefix=key_prefix)(view_func)(request, *args, **kwargs)
            else:
                return view_func(request, *args, **kwargs)
        return _wrapped_view
    return decorator

它在 Django 1 之前一直运行良好7.x。但是,随着 Django 1.8 的更新,我收到以下错误:

Internal Server Error: /
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 223, in get_response
    response = middleware_method(request, response)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/middleware.py", line 55, in process_response
    httponly=settings.SESSION_COOKIE_HTTPONLY or None)
  File "/usr/local/lib/python2.7/dist-packages/django/http/response.py", line 235, in set_cookie
    self.cookies[key] = value
TypeError: 'str' object does not support item assignment

cookies 字典似乎有问题,这里似乎是一个字符串。知道如何解决这个问题吗?

Cookie 的工作方式在 1.8 中已更改,但您的缓存页面仍 returns 1.7 格式。只需清除缓存即可修复它。