【问题标题】:Django: How to get a static file's filepath in a development environment?Django:如何在开发环境中获取静态文件文件路径?
【发布时间】:2012-02-22 08:10:48
【问题描述】:

先介绍一下背景。我正在使用以下“技巧”来防止浏览器对静态文件(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不匹配。在生产中,这会极大地混淆用户;在开发中,这会使我和其他开发人员感到困惑,并迫使我们频繁刷新页面/清除浏览器缓存。)

【问题讨论】:

    标签: python django static-files


    【解决方案1】:

    如果使用 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)))
    

    【讨论】:

    • 啊,finders.find() 正是我所需要的。谢谢,我的模板标签现在可以工作了!我稍后会发布工作代码。
    • 选项未定义
    猜你喜欢
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2018-07-07
    • 1970-01-01
    • 2014-05-26
    相关资源
    最近更新 更多