AttributeError:模块“ http.server”没有属性“ ThreadingHTTPServer”

时间:2018-07-12 08:34:23

标签: python python-3.x httpserver

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

网站上发布的代码为:

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

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

  

此类( ThreadingHTTPServer )与HTTPServer相同,但是使用线程通过ThreadingMixIn处理请求。这对于处理预打开套接字的Web浏览器很有用,HTTPServer会无限期地等待这些套接字。

因此,我将上面的代码更改为:

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,所以我可能错过了一些东西。

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

1 个答案:

答案 0 :(得分:2)

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

  

类http.server.ThreadingHTTPServer(server_address,   RequestHandlerClass)

     

此类与HTTPServer相同,但是使用线程通过ThreadingMixIn处理请求。这对于处理网络很有用   浏览器预打开套接字,HTTPServer将在套接字上等待   无限期地。

     

3.7版中的新功能。 <-this

您可能没有最新版本。