Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在inclusion_标记中缓存模板_Python_Django_Caching - Fatal编程技术网

Python 如何在inclusion_标记中缓存模板

Python 如何在inclusion_标记中缓存模板,python,django,caching,Python,Django,Caching,我试图在inclusion_标记中缓存整个模板,但我有问题 这是我的包含代码\u标签: @register.inclusion_tag('accounts/helpers/user_info.html', takes_context=True) def user_info(context, username, size=40): request = context['request'] user = cache.get(username) if not user:

我试图在inclusion_标记中缓存整个模板,但我有问题

这是我的包含代码\u标签:

@register.inclusion_tag('accounts/helpers/user_info.html', takes_context=True)
def user_info(context, username, size=40):
    request = context['request']

    user = cache.get(username)

    if not user:
        user = User.objects.get(pk=username)
        print("cached")
        cache.set(
            username,
            user,
            settings.USER_LAST_ACTIVITY_TIMEOUT)

    return {'user': user, 'size': size}
html模板的名称和代码:

{% load static i18n humanize accounts cache %}
{% get_current_language as LANGUAGE_CODE %}

{% cache 3600 user_info user.pk LANGUAGE_CODE size %}
<a class="user-info" href="{{ user.get_absolute_url }}">
    <div class="user-avatar-wrapper">
        <span class="online-status {{ user.online_status }}"></span>
        {% if size %}
            {% avatar user size class="avatar" id="user_avatar" %}
        {% else %}
            {% avatar user 40 class="avatar" id="user_avatar" %}
        {% endif %}
    </div>
    <span>
        {{ user }}
        <small>{{ user.groups.all|join:", " }}</small>
    </span>
</a>
{% endcache %}
{%load static i18n humanize accounts cache%}
{%get_当前语言为语言代码%}
{%cache 3600 user\u info user.pk LANGUAGE\u CODE size%}
{%endcache%}
使用这段代码,我只缓存用户,但我想在标记中缓存整个模板。你能帮我怎么做吗?我什么都试过了,但我不知道怎么处理

谢谢

我使用简单标签:

@register.simple_tag(takes_context=True)
def user_info(context, username, size=40):
    tpl = cache.get(username)
    if not tpl:
        user = User.objects.get(pk=username)
        template = loader.get_template('app/user_info.html')
        tpl = template.render({'user': user, 'size': size})
        cache.set(username, tpl)
    return tpl

很抱歉这么说,但你真的是在浪费时间。在这里这些琐碎的查询不应该被缓存。缓存模板呈现也不会加快它们的速度。
User.objects.get(pk=username)
您正在使用主键获取单个项目,这与从memcached获取项目的速度一样快。如果我想。。。。怎么做?请告诉我。谢谢:)