【发布时间】:2020-06-26 03:05:16
【问题描述】:
到目前为止,我几乎只将 render_template() 用于我的烧瓶应用程序路由。 render_template() 直接使用烧瓶时效果很好:
<!-- demo_template.html -->
<!doctype html>
<form action="/">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
DEBUG = 1
HOST = '0.0.0.0'
PORT = 8080
def append_to_file(filename, self):
with open(filename, "a") as text_file:
text_file.write("\n%s" % self)
@app.route('/')
def hello():
args_dict = dict(request.args)
if 'name' in args_dict.keys():
append_to_file('templates/demo_template.html', '<p>'+args_dict['name']+'</p>')
return render_template('demo_template.html',**args_dict)
if __name__ == '__main__':
app.run(debug = DEBUG, host=HOST, port=PORT)
一旦我把 Gunicorn 放在它前面,基本功能就可以工作,但是在重新启动工作程序之前,不会返回附加的内容(名称)。看起来 Gunicorn 缓存了模板。
sudo gunicorn -b 0.0.0.0:8090 app_demo:app -w 1 --log-level=debug --reload
在每次请求(--max-requests 1)后重新启动工作器似乎会重新加载模板并显示附加内容:
sudo gunicorn -b 0.0.0.0:8090 app_demo:app -w 1 --log-level=debug --reload --max-requests 1
这是 Gunicorn 中的错误还是预期的这种行为。我在 Gunicorn 文档中没有看到任何关于这种行为的内容。有没有办法让 gunicorn 在渲染时读取文件而无需重新启动工作人员?
编辑:好的,现在我找到了解决这个问题的两种方法。
- 使用 Gunicorns --reload-extra 选项
- 最快
sudo gunicorn -b 0.0.0.0:8090 app_demo:app -w 1 --log-level=debug --reload --reload-extra templates/demo_template.html - 在烧瓶组内app.jinja_env.auto_reload = True
- 比使用 --max-requests 1 快,比使用 Gunicorn --reload-extra 选项慢
app = Flask(__name__) DEBUG = 1 HOST = '0.0.0.0' PORT = 8080 app.jinja_env.auto_reload = True
【问题讨论】:
-
您可能需要使用它 --> docs.gunicorn.org/en/stable/settings.html#reload-extra-files 因为您正在动态更新应用程序的代码,并且 gunicorn 必须重新启动才能重新加载它
-
@gold_cy 谢谢,不知道我是怎么错过的。如此简单的修复。我还发现将它放在烧瓶应用程序中也可以
app.jinja_env.auto_reload = True尽管由于某种原因响应时间较慢。
标签: python-3.x flask jinja2 gunicorn