Python 如何运行提供特定路径的 http 服务器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39801718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:43:20  来源:igfitidea点击:

How to run a http server which serves a specific path?

pythonpython-3.xsimplehttpserver

提问by roipoussiere

this is my Python3 project hiearchy:

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

projet
  \
  script.py
  web
    \
    index.html

From script.py, I would like to run a http server which serve the content of the webfolder.

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

Hereis suggested this code to run a simple http server:

这里建议使用此代码来运行一个简单的 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()

but this actually serve project, not web. How can I specify the path of the folder I want to serve?

但这实际上是发球project,不是web。如何指定我要提供的文件夹的路径?

采纳答案by John Carter

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

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

This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.

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

So you just need to change the current directory prior to starting the server - see os.chdir

所以你只需要在启动服务器之前更改当前目录 - 请参阅 os.chdir

eg:

例如:

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

回答by Jerzy Pawlikowski

If you just want serve static file you can do it by running SimpleHTTPServer module using python 2:

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

 python -m SimpleHTTPServer

Or with python 3:

或者使用 python 3:

 python3 -m http.server

This way you do not need to write any script.

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

回答by Andy Hayden

In Python 3.7 SimpleHTTPRequestHandlercan take a directoryargument:

在 Python 3.7 中SimpleHTTPRequestHandler可以接受一个directory参数

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

and from the command line:

并从命令行:

python -m http.server --directory web


To get a little crazy... you could make handlers for arbitrary directories:

有点疯狂……你可以为任意目录制作处理程序:

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

回答by Jaymon

Just for completeness, here's how you can setup the actual server classes to serve files from an arbitrary directory:

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

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)

Then you can set any arbitrary path in your code:

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

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

回答by Habbie

There's a shorter method:

有一个更短的方法:

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