1

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()

The index.html file is as follows:

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>

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.

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.

EDIT

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

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

4
  • Do you need to send the variable back to the server and store it or do you just want it to increment client side? Commented Oct 30, 2019 at 15:43
  • @TomMillard Hey, yep back to the server, do some some stuff, then reload the index page. Not sure I want to change the URL though ... i.e. /index/variable=101. Perhaps just posting forms back using url_for(index, form=some_form) would be the way to go? Commented Oct 30, 2019 at 15:46
  • PS. variable could be (and is) an object ... just putting an int down for simplicity Commented Oct 30, 2019 at 15:47
  • Depends on whether or not you need it preserved on the server or not. Commented Oct 30, 2019 at 15:59

2 Answers 2

1

You can use Post/Redirect/Get.

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

Form in 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 %}

change app.py to process the form

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)

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

Sign up to request clarification or add additional context in comments.

2 Comments

Cool -- seems sensible approach. What is 'index_cariable.html'?
just a typo, fixed
0

I think you should consider to use React or Vue. Or please use database (MySQL or MongoDB etc) to store persistent data, and dynamically read the data with ajax.

And another solution, using websocket like meteor or nodejs may be nice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.