配置 SimpleHTTPServer 以假定“.html”用于无后缀 URL

Configuring SimpleHTTPServer to assume '.html' for suffixless URLs

如何配置 Python 模块 "SimpleHTTPServer",例如foo.html 打开时,例如http://localhost:8000/foo叫什么?

我不认为你可以配置它来做到这一点...最快的方法是 monkeypatching:

import SimpleHTTPServer
import os

SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path = lambda self, filename: os.getcwd() + filename + ".html"


if __name__ == '__main__':
    SimpleHTTPServer.test()

您可能会破坏目录列表,因此您应该在添加 .html 之前检查路径是否为目录。

您可以在此处查看更详细的示例:

希望对您有所帮助

@Juan Fco。 Roco 的回答主要满足了我的需要,但我最终使用了受 Clokep's solution for his own blog.

启发的解决方案

最相关的部分是my fake_server.py, but the originating call is in my fabfile.py

的内容

fake_server.py

import os
import SimpleHTTPServer

class SuffixHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """
    Overrides the default request handler to assume a suffixless resource is
    actually an html page of the same name. Thus, http://localhost:8000/foo
    would find foo.html.

    Inspired by:
    https://github.com/clokep/clokep.github.io/blob/source/fake_server.py
    """
    def do_GET(self):
        path = self.translate_path(self.path)

        # If the path doesn't exist, assume it's a resource suffixed '.html'.
        if not os.path.exists(path):
            self.path = self.path + '.html'

        # Call the superclass methods to actually serve the page.
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

SimpleHTTPServer.test(SuffixHandler)