You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

static.py 4.4KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. import mimetypes
  6. import posixpath
  7. import re
  8. from pathlib import Path
  9. from django.http import (
  10. FileResponse, Http404, HttpResponse, HttpResponseNotModified,
  11. )
  12. from django.template import Context, Engine, TemplateDoesNotExist, loader
  13. from django.utils._os import safe_join
  14. from django.utils.http import http_date, parse_http_date
  15. from django.utils.translation import gettext as _, gettext_lazy
  16. def serve(request, path, document_root=None, show_indexes=False):
  17. """
  18. Serve static files below a given point in the directory structure.
  19. To use, put a URL pattern such as::
  20. from django.views.static import serve
  21. url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})
  22. in your URLconf. You must provide the ``document_root`` param. You may
  23. also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
  24. of the directory. This index view will use the template hardcoded below,
  25. but if you'd like to override it, you can create a template called
  26. ``static/directory_index.html``.
  27. """
  28. path = posixpath.normpath(path).lstrip('/')
  29. fullpath = Path(safe_join(document_root, path))
  30. if fullpath.is_dir():
  31. if show_indexes:
  32. return directory_index(path, fullpath)
  33. raise Http404(_("Directory indexes are not allowed here."))
  34. if not fullpath.exists():
  35. raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
  36. # Respect the If-Modified-Since header.
  37. statobj = fullpath.stat()
  38. if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
  39. statobj.st_mtime, statobj.st_size):
  40. return HttpResponseNotModified()
  41. content_type, encoding = mimetypes.guess_type(str(fullpath))
  42. content_type = content_type or 'application/octet-stream'
  43. response = FileResponse(fullpath.open('rb'), content_type=content_type)
  44. response["Last-Modified"] = http_date(statobj.st_mtime)
  45. if encoding:
  46. response["Content-Encoding"] = encoding
  47. return response
  48. DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
  49. {% load i18n %}
  50. <!DOCTYPE html>
  51. <html lang="en">
  52. <head>
  53. <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  54. <meta http-equiv="Content-Language" content="en-us">
  55. <meta name="robots" content="NONE,NOARCHIVE">
  56. <title>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</title>
  57. </head>
  58. <body>
  59. <h1>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</h1>
  60. <ul>
  61. {% if directory != "/" %}
  62. <li><a href="../">../</a></li>
  63. {% endif %}
  64. {% for f in file_list %}
  65. <li><a href="{{ f|urlencode }}">{{ f }}</a></li>
  66. {% endfor %}
  67. </ul>
  68. </body>
  69. </html>
  70. """
  71. template_translatable = gettext_lazy("Index of %(directory)s")
  72. def directory_index(path, fullpath):
  73. try:
  74. t = loader.select_template([
  75. 'static/directory_index.html',
  76. 'static/directory_index',
  77. ])
  78. except TemplateDoesNotExist:
  79. t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
  80. c = Context()
  81. else:
  82. c = {}
  83. files = []
  84. for f in fullpath.iterdir():
  85. if not f.name.startswith('.'):
  86. url = str(f.relative_to(fullpath))
  87. if f.is_dir():
  88. url += '/'
  89. files.append(url)
  90. c.update({
  91. 'directory': path + '/',
  92. 'file_list': files,
  93. })
  94. return HttpResponse(t.render(c))
  95. def was_modified_since(header=None, mtime=0, size=0):
  96. """
  97. Was something modified since the user last downloaded it?
  98. header
  99. This is the value of the If-Modified-Since header. If this is None,
  100. I'll just return True.
  101. mtime
  102. This is the modification time of the item we're talking about.
  103. size
  104. This is the size of the item we're talking about.
  105. """
  106. try:
  107. if header is None:
  108. raise ValueError
  109. matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
  110. re.IGNORECASE)
  111. header_mtime = parse_http_date(matches.group(1))
  112. header_len = matches.group(3)
  113. if header_len and int(header_len) != size:
  114. raise ValueError
  115. if int(mtime) > header_mtime:
  116. raise ValueError
  117. except (AttributeError, ValueError, OverflowError):
  118. return True
  119. return False