Connect JavaScript to Python script with Flask

一曲冷凌霜 提交于 2021-02-07 09:00:19

问题


I created an website with HTML/CSS completly on my own. Also use Javascript for events (click on button, ...).

Now i want to connect an python script with it and more important, return the results from python to my website and display (use) them there. Consider something like this:

Website with an input and 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 dont need python for this specific case, but i want to do that)

From my research i believe Flask is the library to do it (?), but i really dont 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.


回答1:


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/




回答2:


I really appreciate your help and time spent. But your answer did not help me in the way I needed it. At that point I had no clue what to do but since I figured it out some time ago (I watched an youtube video...) I thought i share my solution here (stick two strings):

Thats 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 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.



来源:https://stackoverflow.com/questions/59975596/connect-javascript-to-python-script-with-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!