2
我使用python:如何覆蓋SimpleHTTPServer在目錄列表中顯示時間戳?
python -m SimpleHTTPServer
爲內部用戶訪問測試服務器上的數據文件非常簡單的Web服務器。
SimpleHTTPServer
的默認列表非常簡單。它只顯示文件鏈接。
我怎樣才能讓它顯示文件的時間戳呢?我很高興地編寫自定義類SimpleHTTPServer
我使用Python 2.4.3此刻
我使用python:如何覆蓋SimpleHTTPServer在目錄列表中顯示時間戳?
python -m SimpleHTTPServer
爲內部用戶訪問測試服務器上的數據文件非常簡單的Web服務器。
SimpleHTTPServer
的默認列表非常簡單。它只顯示文件鏈接。
我怎樣才能讓它顯示文件的時間戳呢?我很高興地編寫自定義類SimpleHTTPServer
我使用Python 2.4.3此刻
你可以繼承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))
...然後將它添加到目錄列表輸出。
只是意識到var'linkname'並不完全正確。它應該是:linkname = os.path.join(displaypath,displayname)。再次感謝解決方案。 –
'httpd = SocketServer.TCPServer((「」,8000),DirectoryHandler)' 應該是: 'BaseHTTPServer.HTTPServer(server_address,DirectoryHandler)' 在文件頂部額外導入BaseHTTPServer –