Django получает URL хранения манифеста статических файлов в представлении, когда находится в DEV
Получить статический url в представлении можно с помощью:
from django.templatetags.static import static
url = static('x.jpg')
Однако во время разработки я использую django.contrib.staticfiles.storage.StaticFilesStorage, а в производстве - django.contrib.staticfiles.storage.ManifestStaticFilesStorage.
У меня есть скрипт сборки, который связывает некоторые файлы модулей javascript, при импорте требуются хешированные url, во время DEV. Есть ли способ вычислить хэшированное имя файла, когда django settings.STATICFILES_STORAGE является StaticFilesStorage?
Ниже приведен код, который я придумал, но иногда он дает неправильный хэш (сборка static изменяет файлы (например, исходный код map urls), поэтому я думаю, что это изменяет хэш staic файла, если он ссылается на другой static файл):
from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.files.storage import get_storage_class
from django.template import loader
# Here spath = static path, and fpath = file path, mpath = manifest (hashed) path
# fname = filename
def spath_to_fpath(spath):
return finders.find(spath)
def spath_to_mpath(spath):
fpath = spath_to_fpath(spath)
manifest_storage = get_storage_class(
'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
)()
# location is the fpath that spath is relative too, get the fpath and right trim the spath
manifest_storage.location = fpath.rsplit(spath)[0]
app, name = spath.rsplit('/', 1) # The filename
hashed_fname = manifest_storage.hashed_name(name, filename=spath) # filename arg takes a spath
mpath = f"/static/{app}/{hashed_fname}" # Must not end in a slash!
return mpath