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

时间:2016-10-01 00:13:59

标签: python python-3.x simplehttpserver

这是我的Python3项目hiearchy:

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。如何指定要提供的文件夹的路径?

6 个答案:

答案 0 :(得分:24)

https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler

  

此类直接提供当前目录及以下文件   将目录结构映射到HTTP请求。

因此,您只需在启动服务器之前更改当前目录 - 请参阅os.chdir

例如:

import http.server
import socketserver
import os

PORT = 8000

web_dir = os.path.join(os.path.dirname(__file__), 'web')
os.chdir(web_dir)

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

答案 1 :(得分:17)

如果您只想要提供服务静态文件,可以通过使用python 2运行SimpleHTTPServer模块来实现:

 python3 -m http.server

或者使用python 3:

{{1}}

这样您就不需要编写任何脚本了。

答案 2 :(得分:13)

为了完整起见,以下是设置实际服务器类以从任意目录提供文件的方法:

try
    # python 2
    from SimpleHTTPServer import SimpleHTTPRequestHandler
    from BaseHTTPServer import HTTPServer as BaseHTTPServer
except ImportError:
    # python 3
    from http.server import HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler


class HTTPHandler(SimpleHTTPRequestHandler):
    """This handler uses server.base_path instead of always using os.getcwd()"""
    def translate_path(self, path):
        path = SimpleHTTPRequestHandler.translate_path(self, path)
        relpath = os.path.relpath(path, os.getcwd())
        fullpath = os.path.join(self.server.base_path, relpath)
        return fullpath


class HTTPServer(BaseHTTPServer):
    """The main server, you pass in base_path which is the path you want to serve requests from"""
    def __init__(self, base_path, server_address, RequestHandlerClass=HTTPHandler):
        self.base_path = base_path
        BaseHTTPServer.__init__(self, server_address, RequestHandlerClass)

然后您可以在代码中设置任意路径:

web_dir = os.path.join(os.path.dirname(__file__), 'web')
httpd = HTTPServer(web_dir, ("", 8000))
httpd.serve_forever()

答案 3 :(得分:13)

在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()

答案 4 :(得分:0)

有一个较短的方法:

Handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory='/my/dir/goes/here')

答案 5 :(得分:0)

您还可以使用以下命令运行命令行

python3 -m http.server -d web 8000