且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当模板文件更改时重新加载 Flask 应用程序

更新时间:2023-11-20 17:26:16

根据我的经验,模板甚至不需要重新启动应用程序来刷新,因为它们应该每次都从磁盘加载render_template() 被调用.也许您的模板使用方式不同.

In my experience, templates don't even need the application to restart to be refreshed, as they should be loaded from disk everytime render_template() is called. Maybe your templates are used differently though.

要在模板更改(或任何其他文件)时重新加载您的应用程序,您可以将 extra_files 参数传递给 Flask().run(),这是一组要观察的文件名:对这些文件的任何更改都会触发重新加载器.

To reload your application when the templates change (or any other file), you can pass the extra_files argument to Flask().run(), a collection of filenames to watch: any change on those files will trigger the reloader.

示例:

from os import path, walk

extra_dirs = ['directory/to/watch',]
extra_files = extra_dirs[:]
for extra_dir in extra_dirs:
    for dirname, dirs, files in walk(extra_dir):
        for filename in files:
            filename = path.join(dirname, filename)
            if path.isfile(filename):
                extra_files.append(filename)
app.run(extra_files=extra_files)

请参阅此处:http://werkzeug.pocoo.org/docs/0.10/serving/?highlight=run_simple#werkzeug.serving.run_simple