views.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """
  2. Views and functions for serving static files. These are only to be used during
  3. development, and SHOULD NOT be used in a production setting.
  4. """
  5. import os
  6. import posixpath
  7. from django.conf import settings
  8. from django.http import Http404
  9. from django.utils.six.moves.urllib.parse import unquote
  10. from django.views import static
  11. from django.contrib.staticfiles import finders
  12. def serve(request, path, insecure=False, **kwargs):
  13. """
  14. Serve static files below a given point in the directory structure or
  15. from locations inferred from the staticfiles finders.
  16. To use, put a URL pattern such as::
  17. (r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve')
  18. in your URLconf.
  19. It uses the django.views.static.serve() view to serve the found files.
  20. """
  21. if not settings.DEBUG and not insecure:
  22. raise Http404
  23. normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
  24. absolute_path = finders.find(normalized_path)
  25. if not absolute_path:
  26. if path.endswith('/') or path == '':
  27. raise Http404("Directory indexes are not allowed here.")
  28. raise Http404("'%s' could not be found" % path)
  29. document_root, path = os.path.split(absolute_path)
  30. return static.serve(request, path, document_root=document_root, **kwargs)