Django自定义cache_page decorater在第一次运行后返回错误,之后就可以了

问题描述 投票:0回答:1

我为我的应用程序创建了自定义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
django python-decorators django-middleware django-cache django-cache-machine
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()

© www.soinside.com 2019 - 2024. All rights reserved.