HTML button that updates a Python Variable with Flask

Me and a Friend are trying to make a project, but I need to make it so when you click a button on a HTML web page, it updates a Python variable, Note: I do not know JS

I do not think this is possible using any language. (sorry)

I think you could run a POST request to an endpoint (JS side), and have flask modify the variable because of it (Python side).

You can but not directly, you need to use flask anyway.

As @Firepup650 said you need to use a POST request. You can do something simple in your python like:

@app.route('/update_variable', methods=['POST'])
def update_variable():
    global your_variable
    your_variable = request.form['value']
    return 'Success', 200

And in HTML you make a script to work with it:

    document.getElementById("myButton").onclick = function () {
        fetch('/update_variable', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/www-myrepltproject',
            body: 'value=' + Math.random(),  // update the variable to a random value, just change it later.

This is just an example to give you directions.


You don’t necessarily need a POST request

<button onclick=myFunction()>Click Me!</button>
async function myFunction() {
  const a = await fetch("/setvariable?data="+Math.random())
def set_variable():
  my_variable = request.args.get('data')
  return {'success': True}

Note for all these errors, try to reduce contact between python and js, as it will slow your website down. So unless you need to store in a DB or smth I recommend not even contacting the backend.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.