繁体   English   中英

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

[英]Python HTTP Server Serves Two Paths Using Different Kinds of Handlers

从其他 SO 帖子中,很清楚如何从特定目录提供内容,以及如何map 到不同的do_GET处理程序的传入路径

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

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

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

示例如下。 它提供本地计算机上从目录web/到 URL 基本路径/file/的内容,并在用户提供的方法do_GET()本身中使用 URL 基本路径/api处理请求。 最初,代码源自Axel Rauschmayer 博士在 web 上的示例

#!/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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM