我有一个简单的Flask
应用,其中包含一个名为variable
的变量:
from flask import Flask, render_template
app = Flask(__name__)
variable = 100
@app.route('/', methods=['GET'])
@app.route('/index/', methods=['GET'])
def index():
return render_template('index.html', variable=variable)
def main():
app.run(debug=True, port=5000)
if __name__ == '__main__':
main()
index.html
文件如下:
variable = {{ variable }}
<button onclick="setVariable(101);">
set variable to 101
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function setVariable(variable) {
console.log(`variable = ${variable}`);
}
</script>
[setVariable
功能中是否可以设置变量值?,即在此示例中,variable
的值设置为101。
基本上,最终目标是使用按钮动态设置variable
的值,这还将进一步更新variable = {{ variable }}
文件中的index.html
行。
编辑
以下内容暗示您不能执行此操作,必须使用ajax请求或类似的内容。
您可以使用Post/Redirect/Get。
使用index.html
中的表格将值过帐到@app.route('/index/', methods=['GET', 'POST'])
中的app.py
[C0中的表格]
index.html
更改variable = {{ variable }}
<form action="{{ url_for('index') }}" method="post">
<input type="text" value="101" name="variable">
<input type="submit" value="set variable to 101">
</form>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li style="color:red">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
以处理表格
app.py
如果用户尝试发送数字以外的任何内容,则将from flask import Flask, render_template, request, redirect, url_for, flash
app = Flask(__name__)
app.secret_key = b'_1#y2l"F4Q8z\n\xec]/'
variable = 100
@app.route('/', methods=['GET', 'POST'])
@app.route('/index/', methods=['GET', 'POST'])
def index():
global variable
if request.method == "POST":
try:
variable = int(request.form.get("variable"))
return redirect(url_for('index'))
except:
flash("Invalid type for variable")
return redirect(url_for('index'))
return render_template('index.html', variable=variable)
if __name__ == '__main__':
app.run(debug=True, port=5000)
添加到app.secret_key = b'_1#y2l"F4Q8z\n\xec]/'
错误消息
我认为您应该考虑使用flash
或React
。或者请使用数据库(Vue
或MySQL
等)以存储持久数据,并使用ajax动态读取数据。
还有另一种解决方案,使用像MongoDB
或nodejs这样的websocket可能很好。