Last active
August 13, 2019 14:17
-
-
Save jdunck/0fd1dbc720b352b04c8e to your computer and use it in GitHub Desktop.
Get the contents of a django static file, regardless of whether it has been collected
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import posixpath | |
from django.contrib.staticfiles import finders | |
from django.contrib.staticfiles.storage import staticfiles_storage | |
def static_fallback_open(static_path, mode='r'): | |
writing = 'w' in mode or 'a' in mode | |
if writing or staticfiles_storage.exists(static_path): | |
return staticfiles_storage.open(static_path, mode) | |
# fall back to finders path | |
normalized_path = posixpath.normpath(static_path).lstrip('/') | |
absolute_path = finders.find(normalized_path) | |
if absolute_path is None: | |
raise IOError("{0} does not exist".format(static_path)) | |
return open(absolute_path, mode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment