from django.core.exceptions import Http404, ImproperlyConfigured from django.utils.httpwrappers import HttpResponse from django.conf import settings import os import posixpath import urllib import mimetypes def list_directory(path, fullpath): files = os.listdir(fullpath) response = """ Index of %s/

Index of %s/

""" % (path, path)
    for f in files:
        if os.path.isdir(os.path.join(fullpath, f)):
            f += '/'
        response += '%s\n' % (f, f)

    response += """
""" return response def serve(request, path): if not hasattr(settings, 'DOCUMENT_ROOT'): raise ImproperlyConfigured, "DOCUMENT_ROOT not set in settings file" # Clean up path given in URL. # Algorithm taken from SimpleHTTPServer.translate_path() # Should only allow files below DOCUMENT_ROOT to be accessed. path = posixpath.normpath(urllib.unquote(path)) parts = path.split('/') parts = filter(None, parts) path = "" for part in parts: drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): continue # Strip off . and .. path = os.path.join(path, part) fullpath = os.path.join(settings.DOCUMENT_ROOT, path) try: if os.path.isdir(fullpath): response = HttpResponse(list_directory(path, fullpath), mimetype="text/html") else: mimetype = mimetypes.guess_type(fullpath)[0] f = open(fullpath) response = HttpResponse(, mimetype=mimetype) f.close() return response except IOError: raise Http404