我为我的应用程序创建了自定义cache_page
装饰器。它在第一次运行时不起作用并抛出与中间件相关的错误:
content_encoding = response.get("Content-Encoding", "")
AttributeError: 'bool' object has no attribute 'get'
但是在第二次和更进一步的运行中,它可以工作,因为缓存已设置。我安装了 django debug_toolbar 并将 cors 中间件添加到我的中间件中。有人可以帮忙吗?这是我的自定义装饰器功能:
def cache_page(timeout):
"""custom cache page decorator"""
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
print("wrapp", request)
cache_key = hashlib.md5(
iri_to_uri(request.build_absolute_uri()).encode('ascii')
).hexdigest()
cached_data = cache.get(cache_key)
if cached_data is not None:
return cached_data
response = func(request, *args, **kwargs)
if (isinstance(response, Response) and response.status_code in (200, 301, 302, 304)):
cache_timeout = timeout() if callable(timeout) else timeout
if hasattr(response, 'render') and callable(response.render):
response.add_post_render_callback(
lambda r: cache.set(cache_key, r, cache_timeout)
)
else:
cache.set(cache_key, response, cache_timeout)
return response
return wrapper
return decorator