How to connect JavaScript to Python script with Flask?

Question:

I created a website with HTML/CSS. I also used Javascript for events (click on button, …).

Now I want to connect a Python script with it and more importantly, return the results from my Python functions to my website and display (use) them there.

Consider something like this: I have a website with an input field and a button. If you click on the button, a Python script should run which returns if the input is an odd or even number (of course you don’t need Python for this specific case, but that’s what I want to do).

From my research I believe Flask is the library to be used for this, but I really don’t know how to do it. I found very few examples. I would really appreciate if someone could implement the above example or tell me how to do it exactly.

I know there are already some questions about that concept here online, but as I said, with very few examples.

Asked By: LeoFr

||

Answers:

You’re right about Flask being a good solution for this and there are examples and tutorials everywhere. If what you want is just to run a specific function on a button press and get something back in javascript, I’ve put a quick example is below.

# app.py
from flask import Flask, render_template
from flask import jsonify

app = Flask(__name__)

# Display your index page
@app.route("/")
def index():
    return render_template('index.html')

# A function to add two numbers
@app.route("/add")
def add():
    a = request.args.get('a')
    b = request.args.get('b')
    return jsonify({"result": a+b})

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

This can then be run with python app.py and make sure your index.html is in the same directory. Then you should be able to go to http://127.0.0.1/ and see your page load.

This implements a function which adds two numbers, this can be called in your javascript by calling http://127.0.0.1/add?a=10&b=20. This should then return {"result": 30}.

You can grab this in your javascript using the code below and place this code in your buttons on click callback.

let first = 10;
let second = 20;
fetch('http://127.0.0.1/add?a='+first+'&b='+second)
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log("When I add "+first+" and "+second+" I get: " + myJson.result);
  });

This should be the barebone basics, but once you can submit data to Flask and get data back, you now have an interface to run things in Python.

Edit: Full Front-end example

https://jsfiddle.net/4bv805L6/

Answered By: Michael Bauer

I really appreciate time spent on this answer. But the answer did not help me in the way I needed it. At that point I had no clue what to do, but since thenbI figured it out some time ago and I thought I should share my solution here:

That’s app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/stick', methods=['GET', 'POST'])
def stick():
    if request.method == 'POST':
        result = request.form['string1'] + request.form['string2']
        return render_template('index.html', result=result)
    else:   
        return render_template('index.html')

if __name__ == "__main__":
    app.run()

And that’s index.html (put in the folder templates):

<!DOCTYPE html>
<html>
<body>
    <h3> Stick two strings </h3>
    <form action="{{ url_for('stick') }}" method="post">
            <input type="text" name="string1">
            <input type="text" name="string2">
            <input type="submit" value="Go!">
            <p id="result"></p>
    </form>
<script>

document.getElementById("result").innerHTML = "{{result}}"

</script>
</body>
</html>

In the terminal, type in python app.py and it should work.

Answered By: LeoFr