我正在使用
python -m SimpleHTTPServer
作为一个非常简单的 Web 服务器,用于内部用户访问测试服务器上的数据文件。
默认情况下,
SimpleHTTPServer
的列表非常简单,只显示文件链接。我如何使其同时显示文件时间戳?我很乐意编写一个自定义类来扩展
SimpleHTTPServer
。我目前使用的是 Python 2.4.3。
我正在使用
python -m SimpleHTTPServer
SimpleHTTPServer
的列表非常简单,只显示文件链接。SimpleHTTPServer
。SimpleHTTPRequestHandler
:import cgi, os, SocketServer, sys, time, urllib
from SimpleHTTPServer import SimpleHTTPRequestHandler
from StringIO import StringIO
class DirectoryHandler(SimpleHTTPRequestHandler):
def list_directory(self, path):
try:
list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
f.write("<hr>\n<ul>\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
date_modified = time.ctime(os.path.getmtime(fullname))
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
f.write('<li><a href="%s">%s - %s</a>\n'
% (urllib.quote(linkname), cgi.escape(displayname), date_modified))
f.write("</ul>\n<hr>\n</body>\n</html>\n")
length = f.tell()
f.seek(0)
self.send_response(200)
encoding = sys.getfilesystemencoding()
self.send_header("Content-type", "text/html; charset=%s" % encoding)
self.send_header("Content-Length", str(length))
self.end_headers()
return f
httpd = SocketServer.TCPServer(("", 8000), DirectoryHandler)
print "serving at port", 8000
httpd.serve_forever()
list_directory
方法中添加了一行代码: date_modified = time.ctime(os.path.getmtime(fullname))
httpd = SocketServer.TCPServer(("", 8000), DirectoryHandler)
替换为BaseHTTPServer.HTTPServer(server_address, DirectoryHandler)
。 - Joelle Boulet