0

我为我的应用程序创建了自定义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
4

1 回答 1

0

用 Django 2.2b 测试:

我使用了这个 Mixin:

class CacheKeyDispatchMixin:
    def dispatch(self, *args, **kwargs):
        if self.request.method == 'GET' or self.request.method == 'HEAD':
            url_to_cache = '/{0}{1}'.format(get_language(), self.request.get_full_path())
            cache_hash = calculate_xxxhash(url_to_cache)
            data = cache.get(cache_hash)
            if not data:
                response = super(CacheKeyDispatchMixin, self).dispatch(*args, **kwargs)
                if response.status_code == 200:
                    response.render()
                    cache.set(cache_hash, response)
                    logger.info('Cache added {0} ({1})'.format(url_to_cache, cache_hash))
                return response
            logger.info('Cache hit {0} ({1}).'.format(url_to_cache, cache_hash))
            return data

        return super(CacheKeyDispatchMixin, self).dispatch(*args, **kwargs)

基本上你可以render()在缓存它之前调用它。

于 2019-03-08T08:32:17.937 回答