运行 Python 3.6 中的 Flask 开发服务器为 SocketServer 和 ForkingMixIn 引发 ImportError

Running Flask dev server in Python 3.6 raises ImportError for SocketServer and ForkingMixIn

我正在尝试 运行 使用 Python 3.6 的基本 Flask 应用程序。但是,我得到一个 ImportError: cannot import name 'ForkingMixIn'。当 运行 Python 2.7 或 3.5 时,我不会收到此错误。我如何 运行 Flask 使用 Python 3.6?

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"
Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\werkzeug\serving.py", line 65, in <module>
    from SocketServer import ThreadingMixIn, ForkingMixIn
ImportError: No module named 'SocketServer'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ".\fsk.py", line 9, in <module>
    app.run()
  File "C:\Python36\lib\site-packages\flask\app.py", line 828, in run
    from werkzeug.serving import run_simple
  File "C:\Python36\lib\site-packages\werkzeug\serving.py", line 68, in <module>
    from socketserver import ThreadingMixIn, ForkingMixIn
ImportError: cannot import name 'ForkingMixIn'

这是从 Werkzeug 0.11.15 开始修复的。确保你已经安装了最新版本的 Werkzeug。 pip install -U werkzeug.


这是一个已知问题,reported to Werkzeug 预计 Python 3.6。在那个或另一个补丁被合并和发布之前,Werkzeug 的开发服务器不会 运行 on Python 3.6.

Check if OS can fork before importing ForkingMixIn since Python 3.6 will no longer define that when it is not available on the operating system (python/cpython@aadff9b) and ImportError: cannot import name 'ForkingMixIn' will occur.

与此同时,您可以 运行 您的应用程序使用外部 WSGI 服务器,例如 Gunicorn。

pip install gunicorn
gunicorn my_app:app

如果您需要页内调试器(只要您只有 运行 Gunicorn 和一名工人),您可以将您的应用包装在 debug middleware 中。