Ticket #428: static.py

File static.py, 1.8 KB (added by volsung@…, 19 years ago)

static file view

Line 
1from django.core.exceptions import Http404, ImproperlyConfigured
2from django.utils.httpwrappers import HttpResponse
3from django.conf import settings
4import os
5import posixpath
6import urllib
7import mimetypes
8
9def list_directory(path, fullpath):
10 files = os.listdir(fullpath)
11 response = """
12<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
13<html>
14<head>
15 <title>Index of %s/</title>
16</head>
17<body>
18 <h1>Index of %s/</h1>
19 <pre>
20""" % (path, path)
21 for f in files:
22 if os.path.isdir(os.path.join(fullpath, f)):
23 f += '/'
24 response += '<a href="%s">%s</a>\n' % (f, f)
25
26 response += """
27 </pre>
28</body>
29</html>
30"""
31 return response
32
33
34def serve(request, path):
35 if not hasattr(settings, 'DOCUMENT_ROOT'):
36 raise ImproperlyConfigured, "DOCUMENT_ROOT not set in settings file"
37
38 # Clean up path given in URL.
39 # Algorithm taken from SimpleHTTPServer.translate_path()
40 # Should only allow files below DOCUMENT_ROOT to be accessed.
41 path = posixpath.normpath(urllib.unquote(path))
42 parts = path.split('/')
43 parts = filter(None, parts)
44 path = ""
45 for part in parts:
46 drive, part = os.path.splitdrive(part)
47 head, part = os.path.split(part)
48 if part in (os.curdir, os.pardir): continue # Strip off . and ..
49 path = os.path.join(path, part)
50
51 fullpath = os.path.join(settings.DOCUMENT_ROOT, path)
52 try:
53 if os.path.isdir(fullpath):
54 response = HttpResponse(list_directory(path, fullpath),
55 mimetype="text/html")
56 else:
57 mimetype = mimetypes.guess_type(fullpath)[0]
58 f = open(fullpath)
59 response = HttpResponse(f.read(), mimetype=mimetype)
60 f.close()
61
62 return response
63 except IOError:
64 raise Http404
Back to Top