Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 911
SamS Avatar asked Mar 18 '14 00:03

SamS


People also ask

What does Python SimpleHTTPServer do?

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.

Does Python have HTTP server?

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 .

What is Httpserver in Python?

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.


1 Answers

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>
"""
like image 60
Nicu Surdu Avatar answered Sep 27 '22 19:09

Nicu Surdu