2007-10-14 12:10:02 +08:00
|
|
|
"""
|
2007-11-30 13:14:09 +08:00
|
|
|
Views and functions for serving static files. These are only to be used
|
2007-10-14 12:10:02 +08:00
|
|
|
during development, and SHOULD NOT be used in a production setting.
|
|
|
|
"""
|
2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
2007-10-14 12:10:02 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
import mimetypes
|
2005-09-26 02:45:01 +08:00
|
|
|
import os
|
2011-04-04 20:39:21 +08:00
|
|
|
import stat
|
2005-09-26 02:45:01 +08:00
|
|
|
import posixpath
|
2006-03-03 12:53:04 +08:00
|
|
|
import re
|
2012-07-20 21:36:52 +08:00
|
|
|
try:
|
|
|
|
from urllib.parse import unquote
|
|
|
|
except ImportError: # Python 2
|
|
|
|
from urllib import unquote
|
2005-09-26 02:45:01 +08:00
|
|
|
|
2007-10-14 12:10:02 +08:00
|
|
|
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified
|
2011-03-02 18:40:48 +08:00
|
|
|
from django.template import loader, Template, Context, TemplateDoesNotExist
|
2011-03-01 22:28:06 +08:00
|
|
|
from django.utils.http import http_date, parse_http_date
|
2012-02-05 05:01:11 +08:00
|
|
|
from django.utils.translation import ugettext as _, ugettext_noop
|
2007-10-14 12:10:02 +08:00
|
|
|
|
2011-02-14 09:42:26 +08:00
|
|
|
def serve(request, path, document_root=None, show_indexes=False):
|
2005-09-26 02:45:01 +08:00
|
|
|
"""
|
|
|
|
Serve static files below a given point in the directory structure.
|
2005-11-07 05:54:37 +08:00
|
|
|
|
|
|
|
To use, put a URL pattern such as::
|
|
|
|
|
2005-09-26 21:38:49 +08:00
|
|
|
(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'})
|
2005-11-07 05:54:37 +08:00
|
|
|
|
|
|
|
in your URLconf. You must provide the ``document_root`` param. You may
|
2005-09-26 02:45:01 +08:00
|
|
|
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
|
|
|
|
of the directory. This index view will use the template hardcoded below,
|
|
|
|
but if you'd like to override it, you can create a template called
|
2008-12-05 03:33:28 +08:00
|
|
|
``static/directory_index.html``.
|
2005-09-26 02:45:01 +08:00
|
|
|
"""
|
2012-07-20 21:36:52 +08:00
|
|
|
path = posixpath.normpath(unquote(path))
|
2011-02-14 09:42:26 +08:00
|
|
|
path = path.lstrip('/')
|
|
|
|
newpath = ''
|
|
|
|
for part in path.split('/'):
|
|
|
|
if not part:
|
|
|
|
# Strip empty path components.
|
|
|
|
continue
|
|
|
|
drive, part = os.path.splitdrive(part)
|
|
|
|
head, part = os.path.split(part)
|
|
|
|
if part in (os.curdir, os.pardir):
|
|
|
|
# Strip '.' and '..' in path.
|
|
|
|
continue
|
|
|
|
newpath = os.path.join(newpath, part).replace('\\', '/')
|
|
|
|
if newpath and path != newpath:
|
|
|
|
return HttpResponseRedirect(newpath)
|
|
|
|
fullpath = os.path.join(document_root, newpath)
|
|
|
|
if os.path.isdir(fullpath):
|
|
|
|
if show_indexes:
|
|
|
|
return directory_index(newpath, fullpath)
|
2012-06-08 00:08:47 +08:00
|
|
|
raise Http404(_("Directory indexes are not allowed here."))
|
2011-02-14 09:42:26 +08:00
|
|
|
if not os.path.exists(fullpath):
|
2012-06-08 00:08:47 +08:00
|
|
|
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
|
2011-02-14 09:42:26 +08:00
|
|
|
# Respect the If-Modified-Since header.
|
|
|
|
statobj = os.stat(fullpath)
|
|
|
|
mimetype, encoding = mimetypes.guess_type(fullpath)
|
|
|
|
mimetype = mimetype or 'application/octet-stream'
|
|
|
|
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
|
2011-03-02 06:49:10 +08:00
|
|
|
statobj.st_mtime, statobj.st_size):
|
2012-08-23 00:06:03 +08:00
|
|
|
return HttpResponseNotModified()
|
2011-05-27 12:06:23 +08:00
|
|
|
with open(fullpath, 'rb') as f:
|
2012-07-01 03:19:07 +08:00
|
|
|
response = HttpResponse(f.read(), content_type=mimetype)
|
2011-03-02 06:49:10 +08:00
|
|
|
response["Last-Modified"] = http_date(statobj.st_mtime)
|
2011-04-04 20:39:21 +08:00
|
|
|
if stat.S_ISREG(statobj.st_mode):
|
|
|
|
response["Content-Length"] = statobj.st_size
|
2011-02-14 09:42:26 +08:00
|
|
|
if encoding:
|
|
|
|
response["Content-Encoding"] = encoding
|
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
|
|
DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
|
2012-02-05 05:01:11 +08:00
|
|
|
{% load i18n %}
|
2011-04-21 01:40:53 +08:00
|
|
|
<!DOCTYPE html>
|
|
|
|
<html lang="en">
|
2011-02-14 09:42:26 +08:00
|
|
|
<head>
|
|
|
|
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
|
|
|
|
<meta http-equiv="Content-Language" content="en-us" />
|
|
|
|
<meta name="robots" content="NONE,NOARCHIVE" />
|
2012-02-05 05:01:11 +08:00
|
|
|
<title>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</title>
|
2011-02-14 09:42:26 +08:00
|
|
|
</head>
|
|
|
|
<body>
|
2012-02-05 05:01:11 +08:00
|
|
|
<h1>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</h1>
|
2011-02-14 09:42:26 +08:00
|
|
|
<ul>
|
|
|
|
{% ifnotequal directory "/" %}
|
|
|
|
<li><a href="../">../</a></li>
|
|
|
|
{% endifnotequal %}
|
|
|
|
{% for f in file_list %}
|
|
|
|
<li><a href="{{ f|urlencode }}">{{ f }}</a></li>
|
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
"""
|
2012-06-08 00:08:47 +08:00
|
|
|
template_translatable = ugettext_noop("Index of %(directory)s")
|
2011-02-14 09:42:26 +08:00
|
|
|
|
|
|
|
def directory_index(path, fullpath):
|
|
|
|
try:
|
|
|
|
t = loader.select_template(['static/directory_index.html',
|
|
|
|
'static/directory_index'])
|
|
|
|
except TemplateDoesNotExist:
|
|
|
|
t = Template(DEFAULT_DIRECTORY_INDEX_TEMPLATE, name='Default directory index template')
|
|
|
|
files = []
|
|
|
|
for f in os.listdir(fullpath):
|
|
|
|
if not f.startswith('.'):
|
|
|
|
if os.path.isdir(os.path.join(fullpath, f)):
|
|
|
|
f += '/'
|
|
|
|
files.append(f)
|
|
|
|
c = Context({
|
|
|
|
'directory' : path + '/',
|
|
|
|
'file_list' : files,
|
|
|
|
})
|
|
|
|
return HttpResponse(t.render(c))
|
|
|
|
|
|
|
|
def was_modified_since(header=None, mtime=0, size=0):
|
|
|
|
"""
|
|
|
|
Was something modified since the user last downloaded it?
|
|
|
|
|
|
|
|
header
|
|
|
|
This is the value of the If-Modified-Since header. If this is None,
|
|
|
|
I'll just return True.
|
|
|
|
|
|
|
|
mtime
|
|
|
|
This is the modification time of the item we're talking about.
|
|
|
|
|
|
|
|
size
|
|
|
|
This is the size of the item we're talking about.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
if header is None:
|
|
|
|
raise ValueError
|
|
|
|
matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
|
|
|
|
re.IGNORECASE)
|
2011-03-01 22:28:06 +08:00
|
|
|
header_mtime = parse_http_date(matches.group(1))
|
2011-02-14 09:42:26 +08:00
|
|
|
header_len = matches.group(3)
|
|
|
|
if header_len and int(header_len) != size:
|
|
|
|
raise ValueError
|
2012-09-27 03:12:56 +08:00
|
|
|
if int(mtime) > header_mtime:
|
2011-02-14 09:42:26 +08:00
|
|
|
raise ValueError
|
|
|
|
except (AttributeError, ValueError, OverflowError):
|
|
|
|
return True
|
|
|
|
return False
|