6

I have recently been using Python's SimpleHTTPServer to host files on my network. I want a custom 404 Page, so I researched this and got some answers, but I want to still use this script I have. So, what do I have to add to get a 404 page to this script?

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()
SamS
  • 63
  • 1
  • 7
  • Try [this answer](http://stackoverflow.com/a/5587738/2629998) - for your question you'll need to do something like `HandlerClass.error_message_format = ...`. –  Mar 18 '14 at 00:42

1 Answers1

4

You implement your own request handler class and override the send_error method to change the error_message_format only when code is 404:

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()

The default error_message_format is:

# 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>
"""
Nicu Surdu
  • 8,172
  • 9
  • 68
  • 108