在烧瓶中用按钮和javascript设置python变量

问题描述 投票:0回答:2

我有一个简单的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请求或类似的内容。

https://stackoverflow.com/a/43383967/5058116

javascript python-3.x flask jinja2 setter
2个回答
1
投票

您可以使用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]/'错误消息


0
投票

我认为您应该考虑使用flashReact。或者请使用数据库(VueMySQL等)以存储持久数据,并使用ajax动态读取数据。

还有另一种解决方案,使用像MongoDB或nodejs这样的websocket可能很好。

© www.soinside.com 2019 - 2024. All rights reserved.