使用Python的SimpleHTTP在特定上下文中提供文件夹的方法

2024-05-12 14:52:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在不同的上下文中提供文件夹的所有内容。在

示例:我有一个名为“原始”的文件夹索引.html在我的视窗盒子里。如果我在这个文件夹里输入这个

 python -m SimpleHTTPServer

现在我可以访问索引.html来自http://127.0.0.1:8000/index.html

如何编写一个自定义的Python脚本,以便能够提供相同的服务索引.html文件位于http://127.0.0.1:8000/context/index.html


Tags: 文件脚本文件夹http示例内容indexhtml
1条回答
网友
1楼 · 发布于 2024-05-12 14:52:00

像这样,如果您需要更精细的方法(改编自testpython服务器,根据需要使用),只需要将请求路径解析为多个部分:

# a simple custom http server
class TestHandler(http.server.SimpleHTTPRequestHandler):

    def do_GET(self):
        # if the main path is requested
        # load the template and output it
        if  self.path == "/" or self.path == "":
            out = Contemplate.tpl('main', main_template_data)
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(out)))
            self.end_headers()
            self.wfile.write(bytes(out, 'UTF-8'))
            return
        # else do the default behavior for other requests
        return http.server.SimpleHTTPRequestHandler.do_GET(self)


# start the server
httpd = socketserver.TCPServer((IP, PORT), TestHandler)
print("Application Started on http://%s:%d" % (IP, PORT))
httpd.serve_forever()

相关问题 更多 >