Python HTTP服务器使用不同类型的处理程序为两条路径提供服务



从其他SO帖子中,可以清楚地了解如何提供特定目录中的内容,以及如何将传入路径映射到不同的do_GET处理程序。

以与第一个问题相关的方式扩展第二个问题,如何将路径映射到不同类型的处理程序?具体来说,我想将一个路径映射到do_GET处理程序,将另一个映射到仅提供特定目录中的内容。

如果不可能,那么提供这两种不同内容的更简单方法是什么?我知道这两个线程可以在服务器上运行,每个线程为不同的端口提供服务,这不是很好。

通过跟踪Jaymon回答的第一个参考问题中的代码,并合并第二个参考问题的代码,我得到了答案。

样本如下。它在本地机器上从目录web/向URL基本路径/file/提供内容,并在用户提供的方法do_GET()本身中处理具有URL基本路径/api的请求。最初,该代码源于Axel Rauschmayer博士在网络上的一个样本。

#!/usr/bin/env python
# https://2ality.com/2014/06/simple-http-server.html
# https://stackoverflow.com/questions/39801718/how-to-run-a-http-server-which-serves-a-specific-path
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer as BaseHTTPServer
import os
PORT = 8000
class HTTPHandler(SimpleHTTPRequestHandler):
"""This handler uses server.base_path instead of always using os.getcwd()"""
def translate_path(self, path):
if path.startswith(self.server.base_url_path):
path = path[len(self.server.base_url_path):]
if path == '':
path = '/'
else:
#path = '/'
return None
path = SimpleHTTPRequestHandler.translate_path(self, path)
relpath = os.path.relpath(path, os.getcwd())
fullpath = os.path.join(self.server.base_local_path, relpath)
return fullpath
def do_GET(self):
path = self.path
if (type(path) is str or type(path) is unicode) and path.startswith('/api'):
# call local handler
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Send the html message
self.wfile.write("<b> Hello World !</b>")
self.wfile.close()
return
elif (type(path) is str or type(path) is unicode) and path.startswith(self.server.base_url_path):
return SimpleHTTPRequestHandler.do_GET(self)
elif (type(path) is str or type(path) is unicode) and path.startswith('/'):
self.send_response(441)
self.end_headers()
self.wfile.close()
return
else:
self.send_response(442)
self.end_headers()
self.wfile.close()
return
Handler = HTTPHandler
Handler.extensions_map.update({
'.webapp': 'application/x-web-app-manifest+json',
});
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_local_path, base_url_path, server_address, RequestHandlerClass=HTTPHandler):
self.base_local_path = base_local_path
self.base_url_path = base_url_path
BaseHTTPServer.__init__(self, server_address, RequestHandlerClass)
web_dir = os.path.join(os.path.dirname(__file__), 'web')
httpd = HTTPServer(web_dir, '/file', ("", PORT))
print "Serving at port", PORT
httpd.serve_forever()

最新更新