python - 是否可以让 SimpleHTTPServer 提供来自两个不同目录的文件?

标签 python simplehttpserver

如果我执行 python -m SimpleHTTPServer,它会提供当前目录中的文件。

我的目录结构是这样的:

/protected/public
/protected/private
/test

我想在我的 /test 目录中启动服务器,我希望它为 /test 目录中的文件提供服务。但我希望从 /protected/public 目录中提取对服务器的所有以“/public”开头的请求。

例如,对 http://localhost:8000/public/index.html 的请求将提供位于 /protected/public/index.html 的文件

内置服务器是否可行,还是我必须编写自定义服务器?

最佳答案

我认为完全可以做到这一点。您可以在 /test 目录中启动服务器并覆盖 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 + '/index.html'
            else:
                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()

希望这对您有所帮助。

关于python - 是否可以让 SimpleHTTPServer 提供来自两个不同目录的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8234266/

相关文章:

python -m SimpleHTTPServer - 监听 0.0.0.0 :8000 but “Page Not Found”

Python SimpleHTTPServer接收文件

python - 为什么 PyRotationWarper.warp 和 PyRotationWarper.warpPoint 似乎应用不同的变换?

python - xgboost 二元逻辑回归

java - 如何让HttpServer识别Java中的特殊字符?

python - 如何使用 SimpleHttpRequestHandler 运行 python

python - 同情 : expression simplification

python - 根据百分比水平拆分 2D numpy 数组

python - 两个 IoT 应用程序能否同时访问一个蜂窝调制解调器,这样我就不必杀死 ModemManager 并失去我的互联网连接?

python - 将参数传递给 SimpleHTTPRequestHandler