2017-04-18 14 views
0

我參與了使用whitenoise來提供靜態文件的應用程序。它被配置爲使用CompressedManifestStaticFilesStorage,後者又使用ManifestStaticFilesStorage如何使用ManifestStaticFilesStorage排除散列路徑

通過靜態文件,我指的是我們提供的靜態文件,以及來自第三方的庫,如leaflet

由Django提供的ManifestStaticFilesStorage類將重命名文件名以包含散列。對於cachebusting。它過濾資源並更改對文件的非哈希引用以包含哈希。

這又打破了小葉的功能:

_detectIconPath: function() { 
    var el = DomUtil.create('div', 'leaflet-default-icon-path', document.body); 
    var path = DomUtil.getStyle(el, 'background-image') || 
       DomUtil.getStyle(el, 'backgroundImage'); // IE8 

    document.body.removeChild(el); 

    return path.indexOf('url') === 0 ? 
     path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '') : ''; 
} 

的問題是的path值看起來類似:

url("https://example.org/static/path/leaflet/dist/images/marker-icon.2273e3d8ad92.png") 

由於文件名不匹配,第二次更換不會做任何事情。這反過來將返回:

https://example.org/static/path/leaflet/dist/images/marker-icon.2273e3d8ad92.png") 

當小葉嘗試將文件名添加到該「目錄」,我們得到:

https://example.org/static/path/leaflet/dist/images/marker-icon.2273e3d8ad92.png")marker-icon.png 

它顯然是錯誤的。

那麼解決方案是什麼?我被告知,我們不應該試圖散列第三方軟件包的文件名,可能會有其他破壞。但是我沒有看到ManifestStaticFilesStorage的任何選項排除某些目錄被散列。

我創建了以下類來嘗試解決此問題。我在設置中引用此類而不是CompressedManifestStaticFilesStorage

class MyStorage(CompressedManifestStaticFilesStorage): 
    """ This class overrides the built in class and turns off file name hashing for selected directories. """ 

    def _nonhashed_name_func(self, name, hashed_files=None): 
     name = posixpath.normpath(name) 
     cleaned_name = self.clean_name(name) 
     return cleaned_name 

    def _url(self, hashed_name_func, name, force=False, hashed_files=None): 
     split = name.split("/") 
     if split[0] in ['bower_components', 'node_modules']: 
      hashed_name_func = self._nonhashed_name_func 
     return super()._url(hashed_name_func=hashed_name_func, name=name, force=force, hashed_files=hashed_files) 

這樣的工作,但似乎是一個有點不雅的解決方案。有沒有人有更好的建議?

回答