Django 是否缓存自定义标签和过滤器?

Does Django cache custom tags and filters?

我有相当数量的自定义模板标签,它们执行各种功能,包括:

所有这些函数都位于一个文件中app/templatetags/custom_tags.py。当我想在模板中使用这些标签之一时,我使用 {% load custom_tags %} 导入所有标签。

但是,在任何给定的模板中实际上只使用了可用标签的一小部分。换句话说,所有这些功能都'loaded'到模板中,但在特定的 Web 请求中只调用了其中的几个。

如果这个问题中有不正确的假设或前提,我深表歉意。我很想更好地理解一般导入 python 代码或具体在 Django 环境中导入代码的含义。

对于 Django <= 1.8:

load 标签定义为 here and actually does the loading here and here. Both places call to get_library, defined here. According to the docstrings there, yes, it caches template tag/filter libraries within the same process in the dictionary initalized here

对于 Django 1.9:

模板标签模块 are now being loaded even earlier, when the parser is instantiated, and the libraries are being stored directly on the parser. Load tags call out to find_library here and here, which just gets the already-loaded tag directly from the parser

除了实际加载 activity

正如 @spectras 在下面指出的那样,无论 Django 版本如何,严格来说,标签的加载行为都是副作用,标签 returns (<=1.8/1.9) a no-op node(<=1.8/1.9) 不会呈现内容——所以就目前而言,并没有真正考虑性能。