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的功能和模板标签很相似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值