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
|
2017-01-07 19:11:46 +08:00
|
|
|
from urllib.parse import unquote
|
2010-10-20 09:33:24 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.staticfiles import finders
|
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
|
|
|
|
2013-11-03 04:12:09 +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::
|
|
|
|
|
2014-08-12 22:54:42 +08:00
|
|
|
from django.contrib.staticfiles import views
|
|
|
|
|
|
|
|
url(r'^(?P<path>.*)$', views.serve)
|
2010-10-20 09:33:24 +08:00
|
|
|
|
|
|
|
in your URLconf.
|
|
|
|
|
2013-06-02 01:24:46 +08:00
|
|
|
It uses the django.views.static.serve() 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:
|
2013-07-31 15:11:49 +08:00
|
|
|
raise Http404
|
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)
|