SamS
SamS

Reputation: 63

Python SimpleHTTPServer 404 Page

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

Upvotes: 6

Views: 10105

Answers (1)

Nicu Surdu
Nicu Surdu

Reputation: 8301

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>
"""

Upvotes: 4

Related Questions