Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` pa
(request, path, document_root=None, show_indexes=False)
| 26 | |
| 27 | |
| 28 | def serve(request, path, document_root=None, show_indexes=False): |
| 29 | """ |
| 30 | Serve static files below a given point in the directory structure. |
| 31 | |
| 32 | To use, put a URL pattern such as:: |
| 33 | |
| 34 | from django.views.static import serve |
| 35 | |
| 36 | path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) |
| 37 | |
| 38 | in your URLconf. You must provide the ``document_root`` param. You may |
| 39 | also set ``show_indexes`` to ``True`` if you'd like to serve a basic index |
| 40 | of the directory. This index view will use the template hardcoded below, |
| 41 | but if you'd like to override it, you can create a template called |
| 42 | ``static/directory_index.html``. |
| 43 | """ |
| 44 | path = posixpath.normpath(path).lstrip("/") |
| 45 | fullpath = Path(safe_join(document_root, path)) |
| 46 | if fullpath.is_dir(): |
| 47 | if show_indexes: |
| 48 | return directory_index(path, fullpath) |
| 49 | raise Http404(_("Directory indexes are not allowed here.")) |
| 50 | if not fullpath.exists(): |
| 51 | raise Http404(_("“%(path)s” does not exist") % {"path": fullpath}) |
| 52 | # Respect the If-Modified-Since header. |
| 53 | statobj = fullpath.stat() |
| 54 | if not was_modified_since( |
| 55 | request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj.st_mtime |
| 56 | ): |
| 57 | return HttpResponseNotModified() |
| 58 | content_type, encoding = mimetypes.guess_type(str(fullpath)) |
| 59 | content_type = content_type or "application/octet-stream" |
| 60 | response = FileResponse(fullpath.open("rb"), content_type=content_type) |
| 61 | response.headers["Last-Modified"] = http_date(statobj.st_mtime) |
| 62 | if encoding: |
| 63 | response.headers["Content-Encoding"] = encoding |
| 64 | return response |
| 65 | |
| 66 | |
| 67 | # Translatable string for static directory index template title. |