我注意到随机一些页面需要 2 到 12 秒才能加载,我安装了调试工具栏,我知道我的查询都是高效的(即没有重复),工具栏显示它们都在毫秒内运行。
我决定关注的一个特定页面是我的搜索页面,它使用了 haystack 和弹性搜索。
我有一个查询 haystack 的函数,我有一个计时器,它在服务器端函数的开头和结尾运行,然后生成查询时间,这个从 0.01 到 0.2 秒变化,无论哪种方式都非常快(下面的视图示例)。但是页面可能需要很长时间才能随机加载。
我在 DJDT 中添加了模板计时面板,但它不支持 Django 2.x,但它仍然显示计时结果从 2000 毫秒到 10000 毫秒+
这使我研究了我在这篇文章中遇到的模板渲染(django:加速模板渲染性能的指南)。虽然我不知道提到的很多事情,但我确实研究了缓存。我已将以下内容添加到我的 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',
]),
],
},
},
]
在我的基本模板中,我有一个菜单,可以根据权限显示或隐藏项目,还可以根据模型中的站点类型呈现菜单,所以我认为缓存是一件好事,因为一旦决定了菜单对于用户并且数据库已被查询,它不会改变。(至少我认为这是我应该做的?)
所以我将以下内容添加到我的基本模板中:
{% 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 %}
所以我的问题是,我在这里有正确的方法吗?我怎么知道侧栏的缓存是否真的有效?除了等待查看页面是否加载缓慢之外,我该如何证明呢?
谢谢
视图.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
})