Debian Codegraph @

django/views/static.py

raw
1 """
2 Views and functions for serving static files. These are only to be used
3 during development, and SHOULD NOT be used in a production setting.
4 """
5
6 import mimetypes
7 import posixpath
8 from pathlib import Path
9
10 from django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified
11 from django.template import Context, Engine, TemplateDoesNotExist, loader
12 from django.utils._os import safe_join
13 from django.utils.http import http_date, parse_http_date
14 from django.utils.translation import gettext as _
15 from django.utils.translation import gettext_lazy
16
17
18 def builtin_template_path(name):
19 """
20 Return a path to a builtin template.
21
22 Avoid calling this function at the module level or in a class-definition
23 because __file__ may not exist, e.g. in frozen environments.
24 """
25 return Path(__file__).parent / "templates" / name
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.
68 template_translatable = gettext_lazy("Index of %(directory)s")
69
70
71 def directory_index(path, fullpath):
72 try:
73 t = loader.select_template(
74 [
75 "static/directory_index.html",
76 "static/directory_index",
77 ]
78 )
79 except TemplateDoesNotExist:
80 with builtin_template_path("directory_index.html").open(encoding="utf-8") as fh:
81 t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string(
82 fh.read()
83 )
84 c = Context()
85 else:
86 c = {}
87 files = []
88 for f in fullpath.iterdir():
89 if not f.name.startswith("."):
90 url = str(f.relative_to(fullpath))
91 if f.is_dir():
92 url += "/"
93 files.append(url)
94 c.update(
95 {
96 "directory": path + "/",
97 "file_list": files,
98 }
99 )
100 return HttpResponse(t.render(c))
101
102
103 def was_modified_since(header=None, mtime=0):
104 """
105 Was something modified since the user last downloaded it?
106
107 header
108 This is the value of the If-Modified-Since header. If this is None,
109 I'll just return True.
110
111 mtime
112 This is the modification time of the item we're talking about.
113 """
114 try:
115 if header is None:
116 raise ValueError
117 header_mtime = parse_http_date(header)
118 if int(mtime) > header_mtime:
119 raise ValueError
120 except (ValueError, OverflowError):
121 return True
122 return False