“惰性负载”来自上下文处理器的数据 [英] "Lazy load" of data from a context processor

查看:107
本文介绍了“惰性负载”来自上下文处理器的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序的每个视图中,我需要准备导航菜单。所以现在在每个视图中,我执行复杂的查询,并将菜单存储在一个传递给模板的字典中。在模板中,我有数据的变量被缓存包围,所以即使查询费用相当高,也不会让我感到困扰。



但是不想在每一个观点重复一遍。我猜想准备菜单的最好的地方是在我自己的上下文处理器中。所以我写了一个,但我注意到,即使我不使用上下文处理器的数据,用于准备菜单的查询也被执行。有没有办法从CP中懒惰加载这样的数据,还是在CP中使用低级缓存?或者可能有一个更好的解决方案我的问题?

解决方案

Django有一个 SimpleLazyObject 。在Django 1.3中,这被 auth上下文处理器源代码)。这使得用户在每个查询的模板上下文中可用,但只有在模板包含 {{user}}

您应该能够在上下文处理器中执行类似的操作。

 $ d $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b 
return {
'result':SimpleLazyObject(complexity_query)


In each view of my application I need to have navigation menu prepared. So right now in every view I execute complicated query and store the menu in a dictionary which is passed to a template. In templates the variable in which I have the data is surrounded with "cache", so even though the queries are quite costly, it doesn't bother me.

But I don't want to repeat myself in every view. I guessed that the best place to prepare the menu is in my own context processor. And so I did write one, but I noticed that even when I don't use the data from the context processor, the queries used to prepare the menu are executed. Is there a way to "lazy load" such data from CP or do I have to use "low level" cache in CP? Or maybe there's a better solution to my problem?

解决方案

Django has a SimpleLazyObject. In Django 1.3, this is used by the auth context processor (source code). This makes user available in the template context for every query, but the user is only accessed when the template contains {{ user }}.

You should be able to do something similar in your context processor.

from django.utils.functional import SimpleLazyObject
def my_context_processor(request):
    def complicated_query():
        do_stuff()
        return result

    return {
        'result': SimpleLazyObject(complicated_query)

这篇关于“惰性负载”来自上下文处理器的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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