2010-10-20 09:33:24 +08:00
|
|
|
"""
|
|
|
|
Views and functions for serving static files. These are only to be used during
|
|
|
|
development, and SHOULD NOT be used in a production setting.
|
|
|
|
|
|
|
|
"""
|
|
|
|
import os
|
|
|
|
import posixpath
|
2012-07-20 21:36:52 +08:00
|
|
|
try:
|
|
|
|
from urllib.parse import unquote
|
|
|
|
except ImportError: # Python 2
|
|
|
|
from urllib import unquote
|
2010-10-20 09:33:24 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2011-02-14 09:42:26 +08:00
|
|
|
from django.http import Http404
|
|
|
|
from django.views import static
|
2010-10-20 09:33:24 +08:00
|
|
|
|
2011-02-14 09:42:26 +08:00
|
|
|
from django.contrib.staticfiles import finders
|
2010-10-20 09:33:24 +08:00
|
|
|
|
2013-02-23 21:59:51 +08:00
|
|
|
def serve(request, path, insecure=False, **kwargs):
|
2010-10-20 09:33:24 +08:00
|
|
|
"""
|
|
|
|
Serve static files below a given point in the directory structure or
|
2011-02-14 09:42:26 +08:00
|
|
|
from locations inferred from the staticfiles finders.
|
2010-10-20 09:33:24 +08:00
|
|
|
|
|
|
|
To use, put a URL pattern such as::
|
|
|
|
|
|
|
|
(r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve')
|
|
|
|
|
|
|
|
in your URLconf.
|
|
|
|
|
2011-02-15 07:45:41 +08:00
|
|
|
It uses the django.views.static view to serve the found files.
|
2010-10-20 09:33:24 +08:00
|
|
|
"""
|
2010-11-12 05:43:49 +08:00
|
|
|
if not settings.DEBUG and not insecure:
|
2011-02-14 09:42:26 +08:00
|
|
|
raise ImproperlyConfigured("The staticfiles view can only be used in "
|
2013-01-29 23:45:40 +08:00
|
|
|
"debug mode or if the --insecure "
|
2011-02-14 09:42:26 +08:00
|
|
|
"option of 'runserver' is used")
|
2012-07-20 21:36:52 +08:00
|
|
|
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
|
2011-02-14 09:42:26 +08:00
|
|
|
absolute_path = finders.find(normalized_path)
|
2011-02-15 07:45:41 +08:00
|
|
|
if not absolute_path:
|
2011-07-05 00:19:54 +08:00
|
|
|
if path.endswith('/') or path == '':
|
|
|
|
raise Http404("Directory indexes are not allowed here.")
|
2011-02-15 07:45:41 +08:00
|
|
|
raise Http404("'%s' could not be found" % path)
|
|
|
|
document_root, path = os.path.split(absolute_path)
|
2011-02-14 09:42:26 +08:00
|
|
|
return static.serve(request, path, document_root=document_root, **kwargs)
|