django 模板context的理解


context作為view與template之間的橋梁,理解它的工作原理對於djagno的模板工作機制至關重要。

class ContextDict(dict):#上下文詞典,由詞典可以通過context找到屬於那個上下文,dicts是列表
    def __init__(self, context, *args, **kwargs):
        super(ContextDict, self).__init__(*args, **kwargs)

        context.dicts.append(self)
        self.context = context

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        self.context.pop()

 class ContextDict(dict)是用來保存數據的,它連接了context與dicts,該類可以作為with語句表達式。

class BaseContext(object):#上下文的基類
    def __init__(self, dict_=None):
        self._reset_dicts(dict_)

    def _reset_dicts(self, value=None):#每個上下文都是以builtins作為第一個元素的
        builtins = {'True': True, 'False': False, 'None': None}
        self.dicts = [builtins]
        if value is not None:
            self.dicts.append(value)

    def __copy__(self):
        duplicate = copy(super(BaseContext, self))
        duplicate.dicts = self.dicts[:]
        return duplicate

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

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

    def push(self, *args, **kwargs):#調用push時會生成一個上下文詞典
        dicts = []
        for d in args:
            if isinstance(d, BaseContext):
                dicts += d.dicts[1:]
            else:
                dicts.append(d)
        return ContextDict(self, *dicts, **kwargs)

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

    def __setitem__(self, key, value):#執行context['var']=var時,是在dicts的最后一個元素添加。
        "Set a variable in the current context"
        self.dicts[-1][key] = value

    def __getitem__(self, key):#從最后一個元素開始查找key對應的值
        "Get a variable's value, starting at the current context and going upward"
        for d in reversed(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[-1][key]

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

    def __contains__(self, key):
        return self.has_key(key)

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

    def setdefault(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            self[key] = default
        return default

    def new(self, values=None):
        """
        Returns a new context with the same properties, but with only the
        values given in 'values' stored.
        """
        new_context = copy(self)
        new_context._reset_dicts(values)
        return new_context

    def flatten(self):
        """
        Returns self.dicts as one dictionary
        """
        flat = {}
        for d in self.dicts:
            flat.update(d)
        return flat

    def __eq__(self, other):
        """
        Compares two contexts by comparing theirs 'dicts' attributes.
        """
        if isinstance(other, BaseContext):
            # because dictionaries can be put in different order
            # we have to flatten them like in templates
            return self.flatten() == other.flatten()

        # if it's not comparable return false
        return False

 class Context(BaseContext):

class RequestContext(Context):

class RenderContext(BaseContext):

Context 與RequestContext的區別:

def __init__(self, dict_=None, autoescape=True,
            current_app=_current_app_undefined,
            use_l10n=None, use_tz=None):

def __init__(self, request, dict_=None, processors=None,
            current_app=_current_app_undefined,
            use_l10n=None, use_tz=None):

由它們的初始化函數的參數來看RenderContext多了一個request,processors,少了autoescape。

Context的update函數分析:

def update(self, other_dict):
        "Pushes other_dict to the stack of dictionaries in the Context"
        if not hasattr(other_dict, '__getitem__'):
            raise TypeError('other_dict must be a mapping (dictionary-like) object.')
        if isinstance(other_dict, BaseContext):#如果other_dict是上下文實例,要把頭與尾去掉,重新生成上下文詞典
            other_dict = other_dict.dicts[1:].pop()
        return ContextDict(self, other_dict)

模板上下文處理器在什么地方調用?在調用結果如何影響context?

class RequestContext(Context):
    """
    This subclass of template.Context automatically populates itself using
    the processors defined in the engine's configuration.
    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=_current_app_undefined,
            use_l10n=None, use_tz=None):
        # current_app isn't passed here to avoid triggering the deprecation
        # warning in Context.__init__.
        super(RequestContext, self).__init__(
            dict_, use_l10n=use_l10n, use_tz=use_tz)
        if current_app is not _current_app_undefined:
            warnings.warn(
                "The current_app argument of RequestContext is deprecated. "
                "Set the current_app attribute of its request instead.",
                RemovedInDjango110Warning, stacklevel=2)
        self._current_app = current_app
        self.request = request
        self._processors = () if processors is None else tuple(processors)
        self._processors_index = len(self.dicts)

        # placeholder for context processors output
        self.update({})

        # empty dict for any new modifications
        # (so that context processors don't overwrite them)
        self.update({})

    @contextmanager
    def bind_template(self, template):#綁定模板時會調用全局的上下文處理器及該請求的。
        if self.template is not None:
            raise RuntimeError("Context is already bound to a template")

        self.template = template
        # Set context processors according to the template engine's settings.
        processors = (template.engine.template_context_processors +
                      self._processors)
        updates = {}
        for processor in processors:
            updates.update(processor(self.request))#每個處理器返回一個詞典,通過調用詞典的更新函數進行合並
        self.dicts[self._processors_index] = updates#self._processors_index為len(self.dicts)

        try:
            yield
        finally:
            self.template = None
            # Unset context processors.
            self.dicts[self._processors_index] = {}

    def new(self, values=None):
        new_context = super(RequestContext, self).new(values)
        # This is for backwards-compatibility: RequestContexts created via
        # Context.new don't include values from context processors.
        if hasattr(new_context, '_processors_index'):
            del new_context._processors_index
        return new_context

 

C:\mez>python manage.py shell
Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]

In [1]: from django.template import context

In [3]: dir(context)
Out[3]:
['BaseContext',
 'Context',
 'ContextDict',
 'ContextPopException',
 'RemovedInDjango110Warning',
 'RenderContext',
 'RequestContext',
 '__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '_builtin_context_processors',
 '_current_app_undefined',
 'contextmanager',
 'copy',
 'make_context',
 'warnings']

In [4]: c=context.Context()

In [5]: c.__dict__
Out[5]:
{'_current_app': <object at 0x1597d08>,
 'autoescape': True,
 'dicts': [{'False': False, 'None': None, 'True': True}],
 'render_context': [{'False': False, 'None': None, 'True': True}],
 'template': None,
 'template_name': 'unknown',
 'use_l10n': None,
 'use_tz': None}

In [6]: c.push()
Out[6]: {}

In [7]: c.__dict__
Out[7]:
{'_current_app': <object at 0x1597d08>,
 'autoescape': True,
 'dicts': [{'False': False, 'None': None, 'True': True}, {}],
 'render_context': [{'False': False, 'None': None, 'True': True}],
 'template': None,
 'template_name': 'unknown',
 'use_l10n': None,
 'use_tz': None}

In [8]: c['page']='welcome'

In [9]: c.__dict__
Out[9]:
{'_current_app': <object at 0x1597d08>,
 'autoescape': True,
 'dicts': [{'False': False, 'None': None, 'True': True}, {'page': 'welcome'}],
 'render_context': [{'False': False, 'None': None, 'True': True}],
 'template': None,
 'template_name': 'unknown',
 'use_l10n': None,
 'use_tz': None}

In [10]: c['menu']='menus'

In [11]: c.__dict__
Out[11]:
{'_current_app': <object at 0x1597d08>,
 'autoescape': True,
 'dicts': [{'False': False, 'None': None, 'True': True},
  {'menu': 'menus', 'page': 'welcome'}],
 'render_context': [{'False': False, 'None': None, 'True': True}],
 'template': None,
 'template_name': 'unknown',
 'use_l10n': None,
 'use_tz': None}

In [12]: c['page']
Out[12]: 'welcome'

In [13]: d={1:2,3:4}

In [14]: c['d']=d

In [16]: c['d']
Out[16]: {1: 2, 3: 4}

In [17]: c.push(d)
Out[17]: {1: 2, 3: 4}

In [18]: c.__dict__
Out[18]:
{'_current_app': <object at 0x1597d08>,
 'autoescape': True,
 'dicts': [{'False': False, 'None': None, 'True': True},
  {'d': {1: 2, 3: 4}, 'menu': 'menus', 'page': 'welcome'},
  {1: 2, 3: 4}],
 'render_context': [{'False': False, 'None': None, 'True': True}],
 'template': None,
 'template_name': 'unknown',
 'use_l10n': None,
 'use_tz': None}

In [19]: c[1]
Out[19]: 2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM