【问题标题】:Disable index files with SimpleHTTPServer使用 SimpleHTTPServer 禁用索引文件
【发布时间】:2017-04-06 00:17:47
【问题描述】:

默认情况下,SimpleHTTPServer 使用index.html 作为索引文件,我想禁用它们并始终显示目录索引。

我该怎么做? document here 对此只字未提

【问题讨论】:

    标签: python http server directoryindex


    【解决方案1】:

    简单的方法:

    将索引文件重命名为其他任何内容

    更复杂的方法:

    您必须使用以下内容覆盖 SimpleHTTPRequestHandlertranslate_path 方法:

    import BaseHTTPServer
    import SimpleHTTPServer
    server_address = ("", 8888)
    PUBLIC_RESOURCE_PREFIX = '/public'
    PUBLIC_DIRECTORY = '/path/to/protected/public'
    
    class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
        def translate_path(self, path):
            if self.path.startswith(PUBLIC_RESOURCE_PREFIX):
                if self.path == PUBLIC_RESOURCE_PREFIX or self.path == PUBLIC_RESOURCE_PREFIX + '/':
                    return PUBLIC_DIRECTORY + path[len(PUBLIC_RESOURCE_PREFIX):]
            else:
                return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self, path)
    
    httpd = BaseHTTPServer.HTTPServer(server_address, MyRequestHandler)
    httpd.serve_forever()
    

    【讨论】:

      【解决方案2】:

      我应该覆盖send_head 方法

      只需禁用以下几行

              for index in "index.html", "index.htm":
                  index = os.path.join(path, index)
                  if os.path.exists(index):
                      path = index
                      break
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-08
        • 2011-09-25
        • 2023-04-03
        • 2011-12-13
        • 2016-12-28
        • 2013-12-24
        • 2017-02-08
        相关资源
        最近更新 更多