Django 是否缓存自定义标签和过滤器?
Does Django cache custom tags and filters?
我有相当数量的自定义模板标签,它们执行各种功能,包括:
- 简单的字符串转换
- 复杂 ui 元素的显示
- 时间戳操作和格式化
- 用户头像的处理和显示
- 等...
所有这些函数都位于一个文件中:app/templatetags/custom_tags.py
。当我想在模板中使用这些标签之一时,我使用 {% load custom_tags %}
导入所有标签。
但是,在任何给定的模板中实际上只使用了可用标签的一小部分。换句话说,所有这些功能都'loaded'到模板中,但在特定的 Web 请求中只调用了其中的几个。
- 就性能而言,这是低效的吗?我是否应该更保守地加载代码——即将我的自定义标签拆分成单独的文件并只加载我需要的子集?
- 或者这无关紧要,因为所有标签都加载到内存中——也就是说,在应用程序其他地方对
{% load custom_tags %}
的后续调用不会导致任何额外的开销?
如果这个问题中有不正确的假设或前提,我深表歉意。我很想更好地理解一般导入 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) 不会呈现内容——所以就目前而言,并没有真正考虑性能。
我有相当数量的自定义模板标签,它们执行各种功能,包括:
- 简单的字符串转换
- 复杂 ui 元素的显示
- 时间戳操作和格式化
- 用户头像的处理和显示
- 等...
所有这些函数都位于一个文件中:app/templatetags/custom_tags.py
。当我想在模板中使用这些标签之一时,我使用 {% load custom_tags %}
导入所有标签。
但是,在任何给定的模板中实际上只使用了可用标签的一小部分。换句话说,所有这些功能都'loaded'到模板中,但在特定的 Web 请求中只调用了其中的几个。
- 就性能而言,这是低效的吗?我是否应该更保守地加载代码——即将我的自定义标签拆分成单独的文件并只加载我需要的子集?
- 或者这无关紧要,因为所有标签都加载到内存中——也就是说,在应用程序其他地方对
{% load custom_tags %}
的后续调用不会导致任何额外的开销?
如果这个问题中有不正确的假设或前提,我深表歉意。我很想更好地理解一般导入 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) 不会呈现内容——所以就目前而言,并没有真正考虑性能。