AttributeError: module 'http.server' has no attribute 'ThreadingHTTPServer'

AttributeError: module 'http.server' has no attribute 'ThreadingHTTPServer'

我正在尝试 Python3 关于 HTTP Server 的 this 文档页面上的代码。

网站上发布的代码是:

def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

此代码有效。我会尝试 ThreadingHTTPServer 所以,正如文档所说:

This class (ThreadingHTTPServer) is identical to HTTPServer but uses threads to handle requests by using the ThreadingMixIn. This is useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely.

所以,我把上面的代码改成了:

def run(server_class=http.server.ThreadingHTTPServer, handler_class=http.server.BaseHTTPRequestHandler$
    PORT = 8000
    server_address = ('', PORT)
    httpd = server_class(server_address, handler_class)
    print("server running on port: ", PORT)
    httpd.serve_forever()

但我收到以下错误:

Traceback (most recent call last):
  File "simple_http_server.py", line 6, in <module>
    def run(server_class=http.server.ThreadingHTTPServer, handler_class=http.server.BaseHTTPRequestHandler):
AttributeError: module 'http.server' has no attribute 'ThreadingHTTPServer'

我想补充一下,我最近才使用Python,所以我可能遗漏了什么。

您认为错误的原因是什么?我哪里做错了?

我想我知道你为什么会遇到这个问题。如果你仔细阅读:

class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)

This class is identical to HTTPServer but uses threads to handle requests by using the ThreadingMixIn. This is useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely.

New in version 3.7. <-this

可能您没有最新版本。