Warm tip: This article is reproduced from stackoverflow.com, please click
flask javascript json python

How to pass data from Flask to Javascript?

发布于 2020-03-27 10:16:47

I have been trying to make a basic flask app. I returned the string processed text in the jasonify format in the app.py file. But I don't know how to receive the particular string value into a java-script variable in the index.html file.

Can anyone help me out with this? The following code is a part of the file app.py:

@app.route('/', methods = ['POST'])
def my_form_post():
    MAX_SEQUENCE_LENGTH = 30

    best_model =  load_model('BalanceNet.h5')
    #data2 = pd.read_csv('train.csv')
    text = request.form['u']
    x = text.split(' ')
    y = [int(k) for k in x]
    data_int_t = pad_sequences([y, [], [], [], []], padding='pre', maxlen=(MAX_SEQUENCE_LENGTH-5))
    data_test = pad_sequences(data_int_t, padding='post', maxlen=(MAX_SEQUENCE_LENGTH))
    y_prob = best_model.predict(data_test)
    processed_text = str(y_prob[0][0])

    return jsonify({'request' : processed_text})
Questioner
Debparna Biswas
Viewed
210
abdusco 2019-07-03 22:39

Here's a proof of concept app for you:


./app.py

from flask import Flask, jsonify, request, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/calc', methods=['POST'])
def calc_estimation():
    text = request.form['text']
    results = process_text(text)
    return jsonify(results)

def process_text(text: str) -> str:
    return [text.upper()] * 10

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

./templates/index.html

<form method="POST" action="/calc" data-calc-form>
    <input type="text" name='text'>
    <button>Calculate</button>
    <pre data-preview></pre>
</form>

<script>
    window.addEventListener('DOMContentLoaded', init);

    function init() {
        const form = document.querySelector('[data-calc-form]');
        const textInput = document.querySelector('[name=text]');
        const preview = document.querySelector('[data-preview]');

        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const text = textInput.value;
            const results = await fetchEstimations(text);
            preview.textContent = JSON.stringify(results, null, 4);
        });
    }

    async function fetchEstimations(text) {
        const payload = new FormData();
        payload.append('text', text);

        const res = await fetch('/calc', {
            method: 'post',
            body: payload
        });
        const estimation = await res.json();
        return estimation;
    }
</script>

When you run the app you get a page like this:
home page

When you enter a text and click calculate you get the result printed into <pre>
results

How you use the JSON response is up to you, here I just displayed it as is.