求等价于python -m http.server的可配置Python GET请求服务器类
等价于
python -m http.server的可配置Python代码实现 你需要的是基于Python标准库的实现,直接复用官方http.server模块里的SimpleHTTPRequestHandler即可——它就是python -m http.server命令背后的核心处理类,已经完整实现了GET请求的静态文件服务逻辑(包括目录列表、文件读取与返回等)。
以下是支持配置地址、端口和目录的完整代码:
from http.server import HTTPServer, SimpleHTTPRequestHandler import argparse import os def main(): parser = argparse.ArgumentParser(description='Simple HTTP static file server') parser.add_argument('--bind', '-b', default='', help='Bind address (default: all interfaces)') parser.add_argument('--port', '-p', type=int, default=8000, help='Service port (default: 8000)') parser.add_argument('--directory', '-d', default=os.getcwd(), help='Root directory for file serving (default: current working directory)') args = parser.parse_args() # 切换到指定目录,SimpleHTTPRequestHandler会以此为根目录提供服务 os.chdir(args.directory) server_address = (args.bind, args.port) httpd = HTTPServer(server_address, SimpleHTTPRequestHandler) print(f"Serving HTTP on {args.bind or '0.0.0.0'} port {args.port} (http://{args.bind or 'localhost'}:{args.port}/) ...") try: httpd.serve_forever() except KeyboardInterrupt: print("\nKeyboard interrupt received, shutting down server.") httpd.server_close() if __name__ == '__main__': main()
说明
- 运行方式和官方命令行工具完全一致,例如:
python your_server_script.py --bind 127.0.0.1 --port 9000 --directory /home/user/docs - 如果不需要命令行参数,直接硬编码配置的话,可以简化成:
from http.server import HTTPServer, SimpleHTTPRequestHandler import os # 直接配置参数 BIND_ADDR = '127.0.0.1' PORT = 9000 SERV_DIR = '/home/user/docs' os.chdir(SERV_DIR) httpd = HTTPServer((BIND_ADDR, PORT), SimpleHTTPRequestHandler) print(f"Serving HTTP on {BIND_ADDR} port {PORT} ...") try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
内容的提问来源于stack exchange,提问作者sherwood
相关产品推荐
相关产品推荐

