Python SimpleHTTPServer 404

时间:2014-03-18 00:06:30

标签: python httpserver simplehttpserver

我最近一直使用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()

1 个答案:

答案 0 :(得分:0)

您实现自己的请求处理程序类,并覆盖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>
"""