1
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
2
# See LICENSE for details.
4
"""Directory listing."""
13
from twisted.web2 import iweb, resource, http, http_headers
15
def formatFileSize(size):
18
elif size < (1024**2):
19
return '%iK' % (size / 1024)
20
elif size < (1024**3):
21
return '%iM' % (size / (1024**2))
23
return '%iG' % (size / (1024**3))
25
class DirectoryLister(resource.Resource):
26
def __init__(self, pathname, dirs=None,
29
defaultType='text/html'):
30
self.contentTypes = contentTypes
31
self.contentEncodings = contentEncodings
32
self.defaultType = defaultType
33
# dirs allows usage of the File to specify what gets listed
36
resource.Resource.__init__(self)
38
def data_listing(self, request, data):
40
directory = os.listdir(self.path)
47
for path in directory:
48
url = urllib.quote(path, '/')
49
fullpath = os.path.join(self.path, path)
51
st = os.stat(fullpath)
54
if stat.S_ISDIR(st.st_mode):
58
'linktext': path + "/",
61
'lastmod': time.strftime("%Y-%b-%d %H:%M", time.localtime(st.st_mtime))
64
from twisted.web2.static import getTypeAndEncoding
65
mimetype, encoding = getTypeAndEncoding(
67
self.contentTypes, self.contentEncodings, self.defaultType)
73
'size': formatFileSize(filesize),
75
'lastmod': time.strftime("%Y-%b-%d %H:%M", time.localtime(st.st_mtime))
81
return '<DirectoryLister of %r>' % self.path
86
def render(self, request):
87
title = "Directory listing for %s" % urllib.unquote(request.path)
89
s= """<html><head><title>%s</title><style>
90
th, .even td, .odd td { padding-right: 0.5em; font-family: monospace}
91
.even-dir { background-color: #efe0ef }
92
.even { background-color: #eee }
93
.odd-dir {background-color: #f0d0ef }
94
.odd { background-color: #dedede }
95
.icon { text-align: center }
103
body { border: 0; padding: 0; margin: 0; background-color: #efefef;}
104
h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;}
105
</style></head><body><div class="directory-listing"><h1>%s</h1>""" % (title,title)
107
s+="<tr><th>Filename</th><th>Size</th><th>Last Modified</th><th>File Type</th></tr>"
109
for row in self.data_listing(request, None):
110
s+='<tr class="%s">' % (even and 'even' or 'odd',)
111
s+='<td><a href="%(link)s">%(linktext)s</a></td><td align="right">%(size)s</td><td>%(lastmod)s</td><td>%(type)s</td></tr>' % row
114
s+="</table></div></body></html>"
115
response = http.Response(200, {}, s)
116
response.headers.setHeader("content-type", http_headers.MimeType('text', 'html'))
119
__all__ = ['DirectoryLister']