如何在 python 3 中创建一个简单的 HTTP 网络服务器来响应生成内容的 GET 请求?

How to create a simple HTTP webserver in python 3 responding to GET request with a generated content?

如何在 python 3 中创建一个简单的 HTTP 网络服务器,以便 return 为 GET 请求生成内容?

我检查了这个问题, ,但建议的解决方案将 return 个文件,这不是我需要的东西。

相反,我的服务器应该使用生成的响应进行响应。

我知道像 Flask 和 Django 这样的框架,但它们对我来说太过分了。我需要最短和最少资源的贪婪代码,它只会 return 为任何请求生成内容。

经过一些研究,我想出了一个最简单的解决方案:

from http.server import HTTPServer, BaseHTTPRequestHandler


class MyRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'My content')


httpd = HTTPServer(('localhost', 5555), MyRequestHandler)
httpd.serve_forever()