| 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 |
""" |
| 6 |
|
| 7 |
import os |
| 8 |
import posixpath |
| 9 |
|
| 10 |
from django.conf import settings |
| 11 |
from django.contrib.staticfiles import finders |
| 12 |
from django.http import Http404 |
| 13 |
from django.views import static |
| 14 |
|
| 15 |
|
| 16 |
def serve(request, path, insecure=False, **kwargs): |
| 17 |
""" |
| 18 |
Serve static files below a given point in the directory structure or |
| 19 |
from locations inferred from the staticfiles finders. |
| 20 |
|
| 21 |
To use, put a URL pattern such as:: |
| 22 |
|
| 23 |
from django.contrib.staticfiles import views |
| 24 |
|
| 25 |
path('<path:path>', views.serve) |
| 26 |
|
| 27 |
in your URLconf. |
| 28 |
|
| 29 |
It uses the django.views.static.serve() view to serve the found files. |
| 30 |
""" |
| 31 |
if not settings.DEBUG and not insecure: |
| 32 |
raise Http404 |
| 33 |
normalized_path = posixpath.normpath(path).lstrip("/") |
| 34 |
absolute_path = finders.find(normalized_path) |
| 35 |
if not absolute_path: |
| 36 |
if path.endswith("/") or path == "": |
| 37 |
raise Http404("Directory indexes are not allowed here.") |
| 38 |
raise Http404("'%s' could not be found" % path) |
| 39 |
document_root, path = os.path.split(absolute_path) |
| 40 |
return static.serve(request, path, document_root=document_root, **kwargs) |