0

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})
3
  • Are you familiar with AJAX requests / fetch API? Commented Jul 3, 2019 at 13:27
  • No, not much. Can you help me out? Commented Jul 3, 2019 at 13:29
  • Do you need to use JSON, i.e. do you want to prevent page from reloading once you submit the form? Commented Jul 3, 2019 at 14:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanka a lot. However it did work with the AJAX requests you mentioned before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.