Django 中的全局变量/变量缓存
在我的网站中,我想在多个页面的侧边栏中向用户展示浏览次数最多的产品类别。
因此,在每个不同的视图中,我有:
variables = RequestContext(request, {
(...)
'most_viewed_cats': calculate_most_viewed_categories()
}
在各种模板
{% include "list_most_viewed_categories" %}
和那个模板中:
<ul>
{% for cat in most_viewed_cats %}
{{ cat.name }}
{% empty %}
</ul>No categories to show.<ul>
{% endfor %}
</ul>
但是,我想每 2 天左右只计算一次most_viewed_categories 值,而不是在每个视图中计算它。
我知道视图可以被缓存,但这更多的是变量缓存。是否可以将此变量缓存在 Django 服务器中的某个位置,并仅在该时间段后更新它?人们会如何去做这件事呢?
谢谢
In my website, I want to present to the user the most viewed product categories in a sidebar, in multiple pages.
so in each different view I have:
variables = RequestContext(request, {
(...)
'most_viewed_cats': calculate_most_viewed_categories()
}
and in the various templates
{% include "list_most_viewed_categories" %}
and in that one:
<ul>
{% for cat in most_viewed_cats %}
{{ cat.name }}
{% empty %}
</ul>No categories to show.<ul>
{% endfor %}
</ul>
However, I would like to calculate the most_viewed_categories value only once every 2 days or so, instead of calculating it in every view.
I know views can be cached, but this is more of a variable caching. Is it possible to cache this variable somewhere in the Django server and renew it only after that period of time? How would one go about doing this?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想在整个站点上重用它,您可能最好创建一个上下文处理器,该处理器始终使用包含查看次数最多的类别的变量填充模板上下文
但无论如何,为了缓存以下值数据库,您需要获取缓存并使用
cache.set
和cache.get
来存储和检索值。If it's something you'd like to reuse across the whole site, you would probably do best to create a context processor that's going to always populate the template context with the variable containing the most viewed categories
But in any case, for caching a value in the database, you'll need to obtain the cache and use
cache.set
andcache.get
to store and retrieve the value.