【问题标题】:django fragment caching for anonymous users only仅针对匿名用户的 django 片段缓存
【发布时间】:2011-04-21 03:45:50
【问题描述】:

我想为匿名用户使用 django 片段缓存,但为经过身份验证的用户提供新鲜数据。这似乎工作正常:

{% if user.is_anonymous %}

    {% load cache %}
    {% cache 300 "my-cache-fragment" %}
        <b>I have to write this out twice</b>
    {% endcache %}

{% else %}

    <b>I have to write this out twice</b>

{% endif %}

唯一的问题是我必须重复要缓存的 html。除了将其放入包含中之外,是否有一些巧妙的方法可以解决这个问题?谢谢。

【问题讨论】:

    标签: django django-templates django-cache


    【解决方案1】:

    尝试将经过身份验证的用户的缓存超时设置为零。

    views.py:

    context = {
        "cache_timeout": 300 if request.user.is_anonymous() else 0,
    }
    

    模板:

    {% load cache %}
    {% cache cache_timeout "my-cache-fragment" %}
        <b>I have to write this only once</b>
    {% endcache %}
    

    【讨论】:

    • 这是a similar answer,它将所有逻辑放在模板中(无论好坏)。
    【解决方案2】:
    {% with cache_timeout=user.is_staff|yesno:"0,300" %}
        {% cache cache_timeout cacheidentifier user.is_staff %}
                your content here
        {% endcache %}
    {% endwith %}
    

    【讨论】:

      【解决方案3】:

      不确定我是否理解问题...

      {% load cache %}
      {% cache 300 "my-cache-fragment" %}
          <b>I have to write this out twice</b>
      {% endcache %}
      
      {% if not user.is_anonymous %}
          <b>And this is the extra uncached stuff for authenticated users</b>
      {% endif %}
      

      【讨论】:

      • 匿名用户和经过身份验证的用户都是一样的。唯一的区别是一个在缓存标签里面,一个在外面。
      • 虽然这是一种有效的方法,但它可能会在不同的情况下中断:例如拥有{% block something %}{% endblock %} 会引发错误(不允许多次使用相同的块标签)
      【解决方案4】:

      您可以通过将额外参数传递给cache 标签来指定缓存,例如:

      {% cache 500 sidebar request.user.is_anonymous %}
      

      查看here 了解更多信息... 但这也会为登录用户缓存数据...

      可能你必须写一个custom template tag。您可以首先检查现有的 cache 标记,然后根据该代码创建自定义标记。但不要忘记,django 缓存非常强大和复杂(比如在模板缓存中支持不同的语言)。

      【讨论】:

        猜你喜欢
        • 2014-02-08
        • 2011-01-06
        • 2012-07-24
        • 2015-11-04
        • 1970-01-01
        • 2012-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多