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()
The SimpleHTTPServer module is a Python module that enables a developer to lay the foundation for developing a web server. However, as sysadmins, we can use the module to serve files from a directory. The module loads and serves any files within the directory on port 8000 by default.
You can run python http server on any port, default port is 8000. Try to use port number greater than 1024 to avoid conflicts. Then open your favourite browser and type localhost:9000 .
Python HTTP server is a kind of web server that is used to access the files over the request. Users can request any data or file over the webserver using request, and the server returns the data or file in the form of a response.
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>
"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With