`
edison0951
  • 浏览: 70608 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

DJANGO深入使用之 ---Contex, RequestContext和Processor

阅读更多
class Context(object):
    "A stack container for variable context"
    def __init__(self, dict_=None, autoescape=True, current_app=None):
        dict_ = dict_ or {}
        self.dicts = [dict_]
        self.autoescape = autoescape
        self.current_app = current_app

    def __repr__(self):
        return repr(self.dicts)

    def __iter__(self):
        for d in self.dicts:
            yield d

    def push(self):
        d = {}
        self.dicts = [d] + self.dicts
        return d

    def pop(self):
        if len(self.dicts) == 1:
            raise ContextPopException
        return self.dicts.pop(0)

    def __setitem__(self, key, value):
        "Set a variable in the current context"
        self.dicts[0][key] = value

    def __getitem__(self, key):
        "Get a variable's value, starting at the current context and going upward"
        for d in self.dicts:
            if key in d:
                return d[key]
        raise KeyError(key)

    def __delitem__(self, key):
        "Delete a variable from the current context"
        del self.dicts[0][key]

    def has_key(self, key):
        for d in self.dicts:
            if key in d:
                return True
        return False

    __contains__ = has_key

    def get(self, key, otherwise=None):
        for d in self.dicts:
            if key in d:
                return d[key]
        return otherwise

    def update(self, other_dict):
        "Like dict.update(). Pushes an entire dictionary's keys and values onto the context."
        if not hasattr(other_dict, '__getitem__'):
            raise TypeError('other_dict must be a mapping (dictionary-like) object.')
        self.dicts = [other_dict] + self.dicts
        return other_dict
 

 

以上是DJANGO中Context的源码,其本质上是一个类似于堆栈的一个容器,拥有PYTHON字典和列表的一些方法,其主要功能是将传入的字典变成CONTEXT对象,送给TEMPLATE对象调用,当然了,我们可以用更快捷的方法如render_to_response(templatename, **kwargs)

接着让我们看看威力强大的RequestContext,下面是RequestContex的源码:

class RequestContext(Context):
    """
    This subclass of template.Context automatically populates itself using
    the processors defined in TEMPLATE_CONTEXT_PROCESSORS.
    Additional processors can be specified as a list of callables
    using the "processors" keyword argument.
    """
    def __init__(self, request, dict=None, processors=None, current_app=None):
        Context.__init__(self, dict, current_app=current_app)
        if processors is None:
            processors = ()
        else:
            processors = tuple(processors)
        for processor in get_standard_processors() + processors:
            self.update(processor(request))

 如上面的英文所说,其主要功能是可以调用Processor对象,在DJANGO project的SETTINGS里面有一个变量为TEMPLATE_CONTEXT_PROCESSORS,里面包含一部分内置的PROCESSOR,下面就来看看他们分别有什么作用吧:

django.contrib.auth.context_processors.auth:在模板里面可以直接使用user,message, perms对象。

perms也就是我们的权限模型哟。

django.core.context_processors.i18n:在模板里面可以直接使用settings的LANGUAGES和 LANGUAGE_CODE

django.core.context_processors.debug:在模板里面可以直接使用settings的DEBUG参数以及强大的sql_queries:它本身是一个字典,其中包括当前页面执行SQL查询所需的时间

django.core.context_processors.media:可以在模板里面使用settings的MEDIA_URL参数

django.core.context_processors.request:可以在模板中使用request对象(是强大的HttpRequset实例)

当然了,如果你觉得这写功能还不够,还可以写自己的PROCESSOR啦,自定义PROCESSOR的限制很少,本质上来说他就是一个PYTHON函数,只需要满足这几个条件就OK了:

1.传入参数必须有HttpRequest 2.返回值必须是个字典,3,使用时在settings的TEMPLATE_CONTEXT_PROCESSORS里申明。

关于Context和RequestContext的内容基本到此了,感觉PROCESSOR的功能和模板标签很相似。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics