使用按钮和JavaScript在Flask中设置python变量 [英] Set a python variable in flask with a button and javascript

查看:89
本文介绍了使用按钮和JavaScript在Flask中设置python变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Flask 应用程序,其中包含一个名为 variable 的变量:

I have a simple Flask app that contains a single variable called 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这个例子.

Is there any way to set the variable value within the setVariable function? i.e. such that the value of variable is set to 101 in this example.

基本上,最终目标是使用按钮动态设置 variable 的值,此按钮还应该更新 variable = {{{variable}} 行> index.html 文件.

Basically the end goal is to dynamically set the value of variable using a button, which should furthermore update the variable = {{ variable }} line in the index.html file.

编辑

以下内容暗示您不能执行此操作,必须使用ajax请求或类似的内容.

The following implies you can not do this and must use an ajax request or something similar.

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

推荐答案

您可以使用发布/重定向/获取.

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

Use a form in index.html to post value to @app.route('/index/', methods=['GET', 'POST']) in app.py

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

Adding app.secret_key = b'_1#y2l"F4Q8z\n\xec]/' to flash error message if user tries to send anything other than numbers

这篇关于使用按钮和JavaScript在Flask中设置python变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆