Question

I always use $ python -m SimpleHTTPServer for fast local static web testing, it works great with index.htm or index.html as index files.

However I need to use default.htm or default.html for the project I'm working on at the moment. Can someone help to write a simple script for it please?

I found the below sample on the web, I hope it could help a little to get started.

import sys, SimpleHTTPServer, BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

SimpleHTTPRequestHandler.protocol_version = "HTTP/1.0"

httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8000), SimpleHTTPRequestHandler)

sa = httpd.socket.getsockname()

print "Serving HTTP on", sa[0], sa[1], "..."

httpd.serve_forever()
Was it helpful?

Solution

Here is one way:

import os
import sys
import SimpleHTTPServer
import BaseHTTPServer

class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if not self.redirect():
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

    def do_HEAD(self):
        if not self.redirect():
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self)

    def redirect(self):
        path = self.translate_path(self.path)
        if os.path.isdir(path):
            for base in "index", "default":
                for ext in ".html", ".htm", ".txt":
                    index = base+ext
                    index_path = os.path.join(path, index)
                    if os.path.exists(index_path):
                        new_path = self.path
                        if not new_path.endswith('/'):
                            new_path += '/'
                        new_path += index

                        self.send_response(302)
                        self.send_header("Location", new_path)
                        self.end_headers()
                        return True
        return False

def test(HandlerClass = MyHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)


if __name__ == '__main__':
    test()

Here is another way.

import os
import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

class MyHTTPRequestHandler(SimpleHTTPRequestHandler):
    def translate_path(self,path):
        path = SimpleHTTPRequestHandler.translate_path(self,path)
        if os.path.isdir(path):
            for base in "index", "default":
                for ext in ".html", ".htm", ".txt":
                    index = path + "/" + base + ext
                    if os.path.exists(index):
                        return index
        return path

def test(HandlerClass = MyHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)


if __name__ == '__main__':
    test()

Finally, here is a package HTTP and HTTPS server, with various useful args. Run this with -h to see the help message.

#!/usr/bin/python2.7

import os
import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

class MyHTTPRequestHandler(SimpleHTTPRequestHandler):
    def translate_path(self,path):
        path = SimpleHTTPRequestHandler.translate_path(self,path)
        if os.path.isdir(path):
            for base in "index", "default":
                for ext in ".html", ".htm", ".txt":
                    index = path + "/" + base + ext
                    if os.path.exists(index):
                        return index
        return path

def test(HandlerClass = MyHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):

    import argparse
    parser = argparse.ArgumentParser(description='Dump ANT files')
    parser.add_argument('-p','--port',
                        type=int,
                        default=8080,
                        help='port number')
    parser.add_argument('-i','--ip',
                        default='',
                        help='IP address to listen on: "" means all')
    parser.add_argument('-d','--docroot',
                        default='.',
                        help='Directory to serve files from')
    parser.add_argument('-s','--https',
                        action='store_true',
                        help='Use HTTPS instead of HTTP')
    parser.add_argument('-c', '--certfile', help='server certificate file')
    parser.add_argument('-k', '--keyfile', help='private key file')
    args = parser.parse_args()
    if os.path.isdir(args.docroot):
        os.chdir(args.docroot)
    else:
        parser.error('Docroot must be a directory')

    proto = 'HTTP'
    server_address = (args.ip, args.port)
    httpd = ServerClass(server_address, HandlerClass)

    if args.https:
        import ssl
        if not args.certfile:
            parser.error('Certificate file must be specified')
        if not os.path.isfile(args.certfile):
            parser.error('Certificate file must exist')
        if not args.keyfile:
            parser.error('Private key file must be specified')
        if not os.path.isfile(args.keyfile):
            parser.error('Private key file must exist')
        httpd.socket = ssl.wrap_socket(
            httpd.socket, 
            server_side=True,
            certfile=args.certfile,
            keyfile=args.keyfile)
        proto = 'HTTPS'

    sa = httpd.socket.getsockname()
    print "Serving %s on %s port %s ..."%(proto, sa[0], sa[1])
    httpd.serve_forever()



if __name__ == '__main__':
    test()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top