python - 如何运行服务于特定路径的 http 服务器?

标签 python python-3.x simplehttpserver

这是我的 Python3 项目层次结构:

projet
  \
  script.py
  web
    \
    index.html

script.py,我想运行一个 http 服务器来提供 web 文件夹的内容。

Here建议使用此代码运行一个简单的 http 服务器:

import http.server
import socketserver

PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()

但这实际上服务于 project,而不是 web。如何指定要服务的文件夹的路径?

最佳答案

在 Python 3.7 中 SimpleHTTPRequestHandler can take a directory argument :

import http.server
import socketserver

PORT = 8000
DIRECTORY = "web"


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)


with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

从命令行:

python -m http.server --directory web

有点疯狂...您可以为任意目录创建处理程序:

def handler_from(directory):
    def _init(self, *args, **kwargs):
        return http.server.SimpleHTTPRequestHandler.__init__(self, *args, directory=self.directory, **kwargs)
    return type(f'HandlerFrom<{directory}>',
                (http.server.SimpleHTTPRequestHandler,),
                {'__init__': _init, 'directory': directory})


with socketserver.TCPServer(("", PORT), handler_from("web")) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

关于python - 如何运行服务于特定路径的 http 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39801718/

相关文章:

python - 如何将一列乘以另一列乘以该月第一天的值

python - 在元组列表列表中查找重复项 Python

python - 如何在Python中结合使用base32和hotp(一次性密码)?

python - Python 中的嵌入式 Web 服务器?

Python SimpleHTTPServer接收文件

python - 如何在我的程序中获得除数之和?

Python 浮点格式 - 类似于 "g",但数字更多

python-3.x - Python 3.6.1 安装位置

python - 不带前导零的日期时间对象

python - 是否可以在 python 中使用 http.server 显示目录中的文件大小?