javascriptpythonflaskweb-frameworks

How to connect JavaScript to Python script with Flask?


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.


Solution

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