我最近一直在使用Python的SimpleHTTPServer在我的网络上托管文件。我想要一个自定义404页面,所以我研究了这个,并得到了一些答案,但我想仍然使用这个脚本我有。那么,我需要添加什么来获得这个脚本的404页面呢?
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 80
server_address = ('192.168.1.100', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Being served on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
您实现自己的请求处理程序类并重写send_error
方法以仅在代码为404时更改error_message_format
:
import os
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class MyHandler(SimpleHTTPRequestHandler):
def send_error(self, code, message=None):
if code == 404:
self.error_message_format = "Does not compute!"
SimpleHTTPRequestHandler.send_error(self, code, message)
if __name__ == '__main__':
httpd = HTTPServer(('', 8000), MyHandler)
print("Serving app on port 8000 ...")
httpd.serve_forever()
默认error_message_format
为:
# Default error message template
DEFAULT_ERROR_MESSAGE = """
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code %(code)d.
<p>Message: %(message)s.
<p>Error code explanation: %(code)s = %(explain)s.
</body>
"""