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



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

projet
  
  script.py
  web
    
    index.html

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

建议使用下面的代码运行一个简单的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可以接受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()

和从命令行:

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

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

 python -m SimpleHTTPServer

或python 3:

 python3 -m http.server

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

您也可以使用

运行命令行
python3 -m http.server -d web 8000

Python 3+有一个更短的方法:

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

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

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

另一种从特定目录提供服务的简单方法。

由于您实际上只需要为SimpleHTTPRequestHandler设置directory参数,因此您可以使用functools。对的部分准备处理程序类而不实例化该类。

from functools import partial
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path

def start_httpd(directory: Path, port: int = 8000):
    print(f"serving from {directory}...")
    handler = partial(SimpleHTTPRequestHandler, directory=directory)
    httpd = HTTPServer(('localhost', port), handler)
    httpd.serve_forever()
    

如果你只需要一个现代的web 静态服务器
deno是没有codefile server的替代品。

用单行安装deno

https://github.com/denoland/deno_install deno_install

用单行安装file server

deno install --allow-net --allow-read https://deno.land/std@0.125.0/http/file_server.ts

使用deno file-server

file_server . --port=<port>
# Downloading https://deno.land/std@0.125.0/http/file_server.ts...
# HTTP server listening on http://0.0.0.0:<port>/

阅读更多https://deno.land/manual/examples/file_server#using-the-codestdhttpcode-file-server

相关内容

  • 没有找到相关文章

最新更新