python - SimpleHTTPServer 添加 default.htm default.html 到索引文件

标签 python simplehttpserver

我总是使用 $ python -m SimpleHTTPServer 进行快速本地静态 Web 测试,它与 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()

最佳答案

这是一种方法:

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 服务器包。使用 -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()

关于python - SimpleHTTPServer 添加 default.htm default.html 到索引文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25042076/

相关文章:

python - 全局更改记录器模块中的日志文件名

python - Path().stat().st_mtime 时区?

python - python -m http.server 可以配置为处理并发请求吗?

python - python的SimpleHTTPServer do_GET和do_POST函数如何工作?

python - 如何在 Docker 容器上运行 Python 服务器

Java ServerSocket/socket 与默认网页进行多聊天

python - 查找文本文件中最长的单词

python - 在 Sympy 中对总和进行微分

python - 无法导入 zc.buildout 中的设置

python - 本地服务器提供错误的文件。我有可能运行 2 个 python 服务器吗?