【问题标题】:Set a python variable in flask with a button and javascript使用按钮和 javascript 在烧瓶中设置 python 变量
【发布时间】:2019-10-30 15:21:44
【问题描述】:

我有一个简单的 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 的值,该按钮还应更新index.html 文件中的variable = {{ variable }} 行。

编辑

以下暗示你不能这样做,必须使用 ajax 请求或类似的东西。

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

【问题讨论】:

  • 您需要将变量发送回服务器并存储它还是只是希望它增加客户端?
  • @TomMillard 嘿,是的,回到服务器,做一些事情,然后重新加载索引页面。不确定我是否要更改 URL ...即/index/variable=101。也许只是使用url_for(index, form=some_form) 发回表单就可以了?
  • 附言。 variable 可能是(并且是)一个对象......为了简单起见,只需放下 int
  • 取决于你是否需要将它保存在服务器上。

标签: javascript python-3.x flask jinja2 setter


【解决方案1】:

您可以使用Post/Redirect/Get

使用index.html 中的表单将值发布到app.py 中的@app.route('/index/', methods=['GET', 'POST'])

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 错误消息

【讨论】:

  • 酷——似乎是明智的做法。 'index_cariable.html' 是什么?
  • 只是一个错字,已修复
【解决方案2】:

我认为您应该考虑使用ReactVue。或者请使用数据库 (MySQL or MongoDB etc) 来存储持久化数据,并通过ajax动态读取数据。

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

【讨论】:

    猜你喜欢
    • 2017-04-22
    • 2013-11-16
    • 2020-12-21
    • 1970-01-01
    • 2020-11-19
    • 2019-01-04
    • 2017-10-15
    • 2019-10-25
    • 1970-01-01
    相关资源
    最近更新 更多