How to connect JavaScript to Python script with Flask?
Asked Answered
B

2

6

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.

Beadle answered 29/1, 2020 at 21:7 Comment(1)
The Flask docs now has a full example: flask.palletsprojects.com/en/2.2.x/patterns/javascriptBlowtube
B
5

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.

Beadle answered 12/2, 2020 at 10:53 Comment(2)
Can you please share your folder structure as well as the codes in a github repo or here? I am also facing the issue as like as you but cannot get rid of the problem. My goal is to run a Python Script from the Client side and I am thinking to use Flask as a interim medium. Apart from this, you have written to write on the terminal python stackpy.py. Is it correct or it will be python app.py?Novobiocin
@user10634362 if you wanted to run python on the cilentside, then the user has to install Python! If you wanted to run random code on the server-side as submitted by the cilent. I think that represents a problem in your design. Python can do anything including delete files. And I'm no expert on how to limit what operations your flask server can do.Engagement
D
11

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/

Diapositive answered 29/1, 2020 at 21:56 Comment(5)
much appreciated! However could you be more precise about he index.html file? I have somewhat of an hard time following the tutorials as they are not very clear. I need one complete example where I don`t need do add anything in order to understand working with flask. Thank you!Beadle
Take a look here: jsfiddle.net/4bv805L6 this will work when flask isn't running for a demo, but once flask is running, make sure you remove lines 13-16 so you can actually see flasks response.Diapositive
Again, thank you for your time spent! But i am even more confused now as i don`t see any flask command in your code example ...Beadle
Running "python app.py" from the directory of these files will start the application. Hope this helps.Diapositive
This is awesome. Thank you for your coding expertise. Upvoted!Engagement
B
5

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.

Beadle answered 12/2, 2020 at 10:53 Comment(2)
Can you please share your folder structure as well as the codes in a github repo or here? I am also facing the issue as like as you but cannot get rid of the problem. My goal is to run a Python Script from the Client side and I am thinking to use Flask as a interim medium. Apart from this, you have written to write on the terminal python stackpy.py. Is it correct or it will be python app.py?Novobiocin
@user10634362 if you wanted to run python on the cilentside, then the user has to install Python! If you wanted to run random code on the server-side as submitted by the cilent. I think that represents a problem in your design. Python can do anything including delete files. And I'm no expert on how to limit what operations your flask server can do.Engagement

© 2022 - 2024 — McMap. All rights reserved.