That's quite easy, it's just basic object oriented programing with Python, nothing directly related to Twisted:
import what you need, subclass the File and DirectoryLister, and override in those what is required to be changed.
Starting rom the code you mention, that gives the piece of code below (check the ## ** Comment ** parts).
Hope that helps you starting.
import os
import cgi
import urllib
import time
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.static import File, DirectoryLister, getTypeAndEncoding, formatFileSize
class MyDirectoryLister(DirectoryLister):
## ** Comment **
## Here you can change the way lines are displayed.
## I just added the "mtime" field, see below how it is defined
linePattern = """<tr class="%(class)s">
<td><a href="%(href)s">%(text)s</a></td>
<td>%(size)s</td>
<td>%(type)s</td>
<td>%(encoding)s</td>
<td>%(mtime)s</td>
</tr>
"""
## ** Comment **
## _getFilesAndDirectories is just a copy of the original function found in the File class,
## with minor modifications
def _getFilesAndDirectories(self, directory):
"""
Helper returning files and directories in given directory listing, with
attributes to be used to build a table content with
C{self.linePattern}.
@return: tuple of (directories, files)
@rtype: C{tuple} of C{list}
"""
files = []
dirs = []
for path in directory:
## ** Comment **
## Do stuff with the file path
## (eg filter 'hidden' files and get the modification time):
if path[0] == ".":
continue
mtime = time.asctime(time.localtime(os.path.getmtime(os.path.join(self.path, path))))
url = urllib.quote(path, "/")
escapedPath = cgi.escape(path)
if os.path.isdir(os.path.join(self.path, path)):
url = url + '/'
dirs.append({'text': escapedPath + "/", 'href': url,
'size': '', 'type': '[Directory]',
'encoding': '',
'mtime': mtime
})
else:
mimetype, encoding = getTypeAndEncoding(path, self.contentTypes,
self.contentEncodings,
self.defaultType)
try:
size = os.stat(os.path.join(self.path, path)).st_size
except OSError:
continue
## ** Comment **
## Add attributes the the "elements" displayed in each line
files.append({
'text': escapedPath, "href": url,
'type': '[%s]' % mimetype,
'encoding': (encoding and '[%s]' % encoding or ''),
'size': formatFileSize(size),
'mtime': mtime,
}
)
return dirs, files
class MyFile(File):
## ** Comment **
## You need need of course to subclass File, and change the minimum required to use your
## DirectoryLister
def directoryListing(self):
return MyDirectoryLister(self.path,
self.listNames(),
self.contentTypes,
self.contentEncodings,
self.defaultType)
root = Resource()
## ** Comment **
## Of course, don't forget to use your class:
root.putChild("foo", MyFile("/tmp"))
root.putChild("bar", MyFile("/lost+found"))
root.putChild("baz", MyFile("/opt"))
factory = Site(root)
reactor.listenTCP(8880, factory)
reactor.run()