Django - 使用模板标签渲染许多模板非常慢 [英] Django - rendering many templates using templatetags is very slow

查看:500
本文介绍了Django - 使用模板标签渲染许多模板非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个带有照片库的页面。每个缩略图都有例如照片,国家,作家等。我使用模板标签(加载指定的模板)渲染这些项目/小部件 - 由于DRY(我在页面上的不同地方单独使用这些项/窗口小部件),所以这样做。



/ p>

我使用django-debug-toolbar进行了一些分析:

  SQL查询:默认为84.81 ms(147查询)

但是:

 总CPU时间:5768.360毫秒

太长不能等待。



经过一番分析,结果证明主要的原因是模板引擎。 >

当我想显示例如150张照片,600个相关项目/小部件正在通过模板呈现。这意味着600个I / O操作甚至更多。将这些小部件移动到主模板可以解决问题,但不保持DRY。



所以我的问题是如何避免这种行为?要干,慢还是不干,快?
我宁愿干,快...

解决方案

经过几个小时的分析和搜索...



感谢您的帮助,但在这种情况下,我认为迄今为止最好的解决方案是使用模板片段缓存



我尝试过它获得了70-80%的速度表现!

  {%load cache%} 
{%cache 360​​0 mywidget_id%
..渲染mywidget被缓存..
{%endcache%}


Say, I have a page with a photo gallery. Each thumbnail has e.g. a photo, country, author and so on. I render these items/widgets using template tags (which load specified templates) - it goes that way because of DRY (I use these items/widgets separately in different places on the page).

And it is very slow.

I have performed some profiling using django-debug-toolbar:

SQL Queries: default 84.81 ms (147 queries)

But:

Total CPU time: 5768.360 msec

Which is too long to wait.

After some analysis it turned out that the main culprit is templating enginge.

When I want to display e.g. 150 photos, 600 associated items/widgets are being rendered via templates. It means 600 I/O operations or even more. Moving these widgets to main template solves the problem, but does not keep DRY.

So my question is how one can avoid such a behaviour? Be DRY and slow or no-DRY and fast? I'd rather be DRY and fast...

解决方案

After several hours of profiling and searching...

Thanks for your help, but in this case it seems to me that the best solution so far is to use Template fragment caching:

I tried it and gained 70-80% speed performance!

{% load cache %}
{% cache 3600 mywidget_id %}
    .. rendered mywidget is cached ..
{% endcache %}

这篇关于Django - 使用模板标签渲染许多模板非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆