首次运行时的Flask:不要在生产环境中使用开发服务器

2024-04-27 11:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在PyCharm社区版中安装了Flask插件,我的Flask应用程序中有一个简单的代码:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>Hello!</h1>'

if __name__ == "__main__":
    app.run(debug=True)

我收到一条信息:

WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead

* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
* Running on http://127.0.0.1:5000/

为什么我运行烧瓶时会出现这个错误?


消息的早期版本为“请勿在生产环境中使用开发服务器。”


Tags: 代码namefrom插件app应用程序flaskserver
2条回答

除非您告诉开发服务器它正在开发模式下运行,否则它将假定您正在生产环境中使用它,并警告您不要使用它。The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure.

通过将FLASK_ENV环境变量设置为development,启用开发模式。

export FLASK_ENV=development
flask run

如果您在PyCharm(或任何其他IDE)中运行,则可以在运行配置中设置环境变量。

默认情况下,开发模式启用调试器和重载程序。如果不需要这些,请将--no-debugger--no-reloader传递给run命令。


不过,这个警告只是一个警告,并不是阻止应用程序运行的错误。如果你的应用程序不工作,你的代码还有其他问题。

The official tutorial discusses deploying an app to production.一个选项是使用Waitress,一个生产WSGI服务器。其他服务器包括Gunicorn和uWSGI。

When running publicly rather than in development, you should not use the built-in development server (flask run). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.

Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:

$ pip install waitress

You need to tell Waitress about your application, but it doesn’t use FLASK_APP like flask run does. You need to tell it to import and call the application factory to get an application object.

$ waitress-serve --call 'flaskr:create_app'
Serving on http://0.0.0.0:8080

或者可以在代码中使用waitress.serve(),而不是使用CLI命令。

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<h1>Hello!</h1>"

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)
$ python hello.py

相关问题 更多 >