SimpleHTTPServer将default.htm default.html添加到索引文件中

时间:2014-07-30 16:27:24

标签: python simplehttpserver

我总是使用$ python -m SimpleHTTPServer进行快速本地静态网络测试,它可以使用index.htmindex.html作为索引文件。

但是,我需要将default.htmdefault.html用于我目前正在处理的项目。有人可以帮忙写一个简单的脚本吗?

我在web上找到了以下示例,我希望它可以帮助您开始使用。

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

1 个答案:

答案 0 :(得分:5)

这是一种方式:

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

这是另一种方式。

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

最后,这是一个包HTTP和HTTPS服务器,带有各种有用的args。使用-h运行此操作以查看帮助消息。

#!/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()