Skip to content

Instantly share code, notes, and snippets.

@jdunck
Last active August 13, 2019 14:17
Show Gist options
  • Save jdunck/0fd1dbc720b352b04c8e to your computer and use it in GitHub Desktop.
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
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