先介绍一些背景。我正在使用以下“技巧”来防止浏览器缓存静态文件(CSS、JS 等):
<script src="{{ STATIC_URL }}js/utils.js?version=1302983029"></script>
当版本字符串在随后的页面加载中发生变化时,它会使浏览器从服务器重新获取静态文件。 (谷歌“css 缓存”获取有关此技巧的文章。)
我希望浏览器获取静态文件的最新版本,但我也希望在文件未更改时允许浏览器缓存。换句话说,当且仅当静态文件已更新时,我希望版本字符串发生变化。我也想自动生成版本字符串。
为此,我使用静态文件的最后修改时间作为版本字符串。我正在制作一个自定义模板标签来执行此操作:
<script src="{% versioned_static 'js/utils.js' %}"></script>
下面是模板标签的工作原理:
import os.path
from django import template
from django.conf import settings
class VersionedStaticNode(template.Node):
...
def render(self, context):
# With the example above, self.path_string is "js/utils.js"
static_file_path = os.path.join(settings.STATIC_ROOT, self.path_string)
return '%s?version=%s' % (
os.path.join(settings.STATIC_URL, self.path_string),
int(os.path.getmtime(static_file_path))
)
要获取静态文件的最后修改时间,我需要知道它在系统上的文件路径。我通过加入 settings.STATIC_ROOT
和该静态根文件的相对路径来获取此文件路径。这对生产服务器来说非常好,因为所有静态文件都收集在 STATIC_ROOT
中。
但是,在开发服务器上(使用 manage.py runserver 命令的地方),静态文件不会收集在 STATIC_ROOT
中。那么在开发中运行时如何获取静态文件的文件路径呢?
(阐明我的目的:我要避免的缓存情况是浏览器使用新的 HTML 和旧的 CSS/JS 不匹配。在生产中,这会使用户非常困惑;在开发中,这会使我和其他开发人员感到困惑,并迫使我们频繁刷新页面/清除浏览器缓存。)
最佳答案
如果使用 django.contrib.staticfiles,这里是 findstatic 的摘录命令(django/contrib/staticfiles/management/commands/findstatic.py)应该有帮助。它使用 finders.find找到文件。
from django.contrib.staticfiles import finders
result = finders.find(path, all=options['all'])
path = smart_unicode(path)
if result:
if not isinstance(result, (list, tuple)):
result = [result]
output = u'\n '.join(
(smart_unicode(os.path.realpath(path)) for path in result))
self.stdout.write(
smart_str(u"Found '%s' here:\n %s\n" % (path, output)))
关于python - Django:如何在开发环境中获取静态文件的文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9391167/