python - BaseHttpServer 和 wsgiref.simple_server 的区别

标签 python basehttpserver wsgiref

我正在寻找一个模块,该模块可为我提供用于本地访问的基本 HTTP 服务器功能。 Python 似乎有两种方法可以在标准库中实现简单的 http 服务器:wsgiref.simple_serverBaseHttpServer .

有什么区别?有充分的理由偏爱其中之一吗?

最佳答案

简答:wsgiref.simple_server 是一个基于 BaseHTTPServer 的 WSGI 适配器。

更长的答案:

BaseHTTPServer(和它构建的 SocketServer )是实现大部分实际 HTTP 服务器的模块。它可以接受请求并返回响应,但它必须知道如何处理这些请求。当您直接使用 BaseHTTPServer 时,您可以通过子类化 BaseHTTPRequestHandler 来提供处理程序,例如:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        self.wfile.write('Hello world!\n')

HTTPServer(('', 8000), MyHandler).serve_forever()

wsgiref.simple_server 将此 BaseHTTPServer 接口(interface)适配到 WSGI规范,这是独立于服务器的 Python Web 应用程序的标准。在 WSGI 中,您以函数的形式提供处理程序,例如:

from wsgiref.simple_server import make_server

def my_app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    yield 'Hello world!\n'

make_server('', 8000, my_app).serve_forever()

make_server 函数返回 WSGIServer 的一个实例,它从 BaseHTTPServer.HTTPServer 继承了大部分实际协议(protocol)/网络逻辑和 SocketServer.TCPServer (尽管它确实最终重新实现了一些简单的 HTTP 规则)。主要区别在于您将应用程序代码与该逻辑集成的方式。

这实际上取决于您要解决的问题,但是针对 wsgiref 进行编码可能是一个更好的主意,因为它可以让您轻松迁移到不同的生产级 HTTP服务器,例如 uWSGIGunicorn , future 。

关于python - BaseHttpServer 和 wsgiref.simple_server 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612290/

相关文章:

python - Pandas 滚动最大与 groupby

python - 为什么要使用 wsgiref simple_server?

python - 守护 python 的 BaseHTTPServer

python - 您将如何在 Python 中模拟 Web 应用程序(用于测试 Django 项目)

jquery - 用于与 jsonp 通信的简单 Python HTTP 服务器

python - 几次请求后 wsgiref.simple_server 出现奇怪的滞后/延迟/延迟/任何问题

python - 已编译 Python 与 IronPython 的启动时间

python - 优化此解决方案以查找公交网络中两个站点之间的最短路径

python - Spyder、变量浏览器、xpt