我正在研究如何用Python开发一个不错的web应用程序。因为我不想让一些高阶结构妨碍我,所以我选择了轻量级的Flask框架。时间会证明这是否是正确的选择。

So, now I've set up an Apache server with mod_wsgi, and my test site is running fine. However, I'd like to speed up the development routine by making the site automatically reload upon any changes in py or template files I make. I see that any changes in site's .wsgi file causes reloading (even without WSGIScriptReloading On in the apache config file), but I still have to prod it manually (ie, insert extra linebreak, save). Is there some way how to cause reload when I edit some of the app's py files? Or, I am expected to use IDE that refreshes the .wsgi file for me?


当前回答

我有不同的想法:

第一:

pip install python-dotenv

安装python-dotenv模块,该模块将读取项目环境的本地首选项。

第二:

在项目目录中添加.flaskenv文件。添加以下代码:

FLASK_ENV=development

这是完成了!

使用此配置为您的Flask项目,当您运行Flask运行时,您将在终端中看到以下输出:

编辑文件时,保存更改即可。你会看到自动重载为你:

更多解释:

当然,您可以在需要的时候手动点击export FLASK_ENV=development。但是使用不同的配置文件来处理实际的工作环境似乎是一个更好的解决方案,所以我强烈推荐我使用的这种方法。

其他回答

I believe a better solution is to set the app configuration. For me, I built the tool and then pushed it to a development server where I had to set up a WSGI pipeline to manage the flask web app. I had some data being updated to a template and I wanted it to refresh every X minutes (WSGI deployment for the Flask site through APACHE2 on UBUNTU 18). In your app.py or whatever your main app is, add app.config.update dictionary below and mark TEMPLATES_AUTO_RELOAD=True, you will find that any templates that are automatically updated on the server will be reflected in the browser. There is some great documentation on the Flask site for configuration handling found here.

app = Flask(__name__)
app.config.update(
    TEMPLATES_AUTO_RELOAD=True
)

如果您正在讨论测试/开发环境,那么只需使用调试选项。当发生代码更改时,它将自动重新加载flask应用程序。

app.run(debug=True)

或者,从壳层来看

$ export FLASK_DEBUG=1
$ flask run

http://flask.palletsprojects.com/quickstart/#debug-mode

对于Flask 1.0到2.2,热重新加载的基本方法是:

$ export FLASK_APP=my_application
$ export FLASK_ENV=development
$ flask run

你应该使用FLASK_ENV=development(而不是FLASK_DEBUG=1) 作为安全检查,你可以运行flask run——debugger来确保它是打开的 Flask CLI现在会自动读取FLASK_APP和FLASK_ENV之类的东西,如果你在项目根目录中有一个.env文件,并且安装了python-dotenv

帮助快速自动更改浏览器:

PIP安装负载

from livereload import Server

if __name__ == '__main__':
    server = Server(app.wsgi_app)
    server.serve()

接下来,再次启动服务器:

如。你的.py文件是app.py

python app.py

启用flask 2.2中的reloader:

flask run --reload