MCPcopy
hub / github.com/django/django / serve

Function serve

django/views/static.py:28–64  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

26
27
28def 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&#x27;d like to serve a basic index
40 of the directory. This index view will use the template hardcoded below,
41 but if you&#x27;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.

Callers 2

serveMethod · 0.90
serve_templateMethod · 0.90

Calls 10

safe_joinFunction · 0.90
Http404Class · 0.90
FileResponseClass · 0.90
http_dateFunction · 0.90
directory_indexFunction · 0.85
was_modified_sinceFunction · 0.85
existsMethod · 0.45
getMethod · 0.45
openMethod · 0.45

Tested by 2

serveMethod · 0.72
serve_templateMethod · 0.72