简体   繁体   English

Django - 模板渲染性能(我认为)如何检查启用 LocMemCache 是否有效?

[英]Django - Template rendering performance (I think) how to check if enabling LocMemCache is working?

Ive noticed that randomly some pages take from 2 to 12 seconds to load, I have Debug toolbar installed and I know my queries are all efficient (ie no duplicates) and toolbar shows they are all running in milliseconds.我注意到随机加载一些页面需要 2 到 12 秒,我安装了调试工具栏,并且我知道我的查询都是高效的(即没有重复),工具栏显示它们都在毫秒内运行。

One particular page ive decide to focus on is my search page which uses haystack and elastic search.我决定关注的一个特定页面是我的搜索页面,它使用了 haystack 和弹性搜索。

I have a function which queries haystack and I have a timer that runs at the beginning of the server side function and the end and then churns out the query time, this Varys from 0.01 to 0.2 seconds, either way pretty fast (example of view below).我有一个查询 haystack 的 function 并且我有一个计时器,它在服务器端 function 的开头和结尾运行,然后产生查询时间,这个变化从 0.01 到 0.2 秒,无论哪种方式都非常快(视图示例)。 but the page can take extremely long to load randomly.但是页面可能需要很长时间才能随机加载。

ive added template timings panel to DJDT however it doesnt support Django 2.x, but it does still show a timings result which was varying from 2000ms to 10000ms+我向 DJDT 添加了模板计时面板,但它不支持 Django 2.x,但它仍然显示从 2000ms 到 10000ms+ 变化的计时结果

Which lead me to research the template rendering where I come across this post ( django: guidelines for speeding up template rendering performance ).这使我研究了我在这篇文章中遇到的模板渲染( django:加速模板渲染性能的指南)。 Whilst im not au fait with a lot of the things that are mentioned, I did look into caching.虽然我不知道提到的很多事情,但我确实研究了缓存。 I have added the below to my settings.py file:我已将以下内容添加到我的 settings.py 文件中:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-gugu-cache',
    }
}

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR + '/templates/',
            ],
        'APP_DIRS': False,
        'OPTIONS': {
            'debug' : DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.request',
                'django.template.context_processors.i18n',
                'itapp.context_processors.site_links',
                'itapp.context_processors.quick_jump_links',
            ],
            'loaders': [
            ('django.template.loaders.cached.Loader', [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ]),
        ],
        },
    },
]

and in my base template I have a menu that shows or hides items based on permissions and also renders a menu based on types of site from a model, so I thought this would be a good thing to cache, as once the menu has been decided for a user and the db has been queried it doesnt change.在我的基本模板中,我有一个菜单,可以根据权限显示或隐藏项目,还可以根据 model 的站点类型呈现菜单,所以我认为这将是一件好事,因为一旦决定了菜单对于用户并且数据库已被查询,它不会改变。 (at least I think this is what I should be doing?) (至少我认为这是我应该做的?)

so I added the below to my base template:所以我将以下内容添加到我的基本模板中:

{% load static %} {% load extras %} {% load i18n %} {% load cache %}
{% cache 500 sidebar %}
{% if user.is_active and user.is_staff %}
 <a class="dropdown-item preview-item" href="{% url 'admin:index' %}">    
    <p class="preview-subject mb-1">{% trans 'Admin' %}</p>
...
 {% if user.is_authenticated %}
...etc all the html and template logic for the side bar
{% end cache %}

So my question is, do I have the correct approach here?所以我的问题是,我在这里有正确的方法吗? and how do I know if the caching of the side bar is actually working or not?我怎么知道侧栏的缓存是否真的有效? other than waiting to see if a page loads slowly or not how can I prove it?除了等待查看页面是否加载缓慢之外,我该如何证明呢?

Thank you谢谢

Views.py视图.py

@login_required
def search(request):
    from haystack.query import SearchQuerySet
    from haystack.inputs import AutoQuery, Exact, Clean
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    start = datetime.now()

    query = request.GET['q']
    sqs = SearchQuerySet().filter(content=AutoQuery(query))

    results = sqs
    result_count = results.count()

    end = datetime.now()
    search_duration = (end - start).total_seconds()

    return render(request, 'search/search_no_pag.html', {
        'result_count' : result_count,
        'query' : query,
        'results': results,  
        'search_duration' : search_duration
    })  

The best results you would get from actually monitoring your application on production.从实际监控生产中的应用程序中获得的最佳结果。 It can be anything starting from HTTP logs with time in it or full fledged APM dedicated to Django that can summarize template rendering per view.它可以是从 HTTP 日志开始的任何内容,其中包含时间或专用于 Django 的完整 APM,可以总结每个视图的模板渲染。

That's how you know:你就是这样知道的:

  1. If you should optimize at all如果你应该优化
  2. What to optimize优化什么
  3. If whatever you've changed actually helped如果你所做的改变真的有帮助
  4. When to stop optimizing何时停止优化

Please look at the example there: https://scoutapm.com/blog/monitoring-a-django-app-with-scout请看那里的例子: https://scoutapm.com/blog/monitoring-a-django-app-with-scout

If the "rendering" part gets smaller after deployment compared to similar working conditions, that is the way you can prove something has helped.如果与类似的工作条件相比,部署后“渲染”部分变得更小,这就是您可以证明某些事情有所帮助的方式。

Starting from Django 1.11 the cached loader is enabled by default if you don't run with DEBUG mode.从 Django 1.11 开始,如果您不使用DEBUG模式运行,则默认启用缓存加载程序。

This loader is automatically enabled if OPTIONS['loaders'] isn't specified and OPTIONS['debug'] is False (the latter option defaults to the value of DEBUG).如果未指定 OPTIONS['loaders'] 并且 OPTIONS['debug'] 为 False(后一个选项默认为 DEBUG 的值),则此加载程序会自动启用。

https://docs.djangoproject.com/en/2.2/ref/templates/api/#django.template.loaders.cached.Loader https://docs.djangoproject.com/en/2.2/ref/templates/api/#django.template.loaders.cached.Loader

Which brings me to my last point: your problems are probably caused by DEBUG mode.这让我想到了最后一点:您的问题可能是由DEBUG模式引起的。 Which brings me to my first sentence: measure performance on production.这让我想到了我的第一句话:衡量生产绩效。

Your problem may be the debug toolbar itself.您的问题可能是调试工具栏本身。 Remove DT and try again, but use another tool like newrelic.删除 DT 并重试,但使用其他工具,如 newrelic。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM