如何将数据从Flask传递到Javascript?

时间:2019-07-03 13:22:33

标签: javascript python json flask

我一直在尝试制作一个基本的烧瓶应用程序。我在processed text文件中以jasonify格式返回了字符串app.py。但是我不知道如何将特定的字符串值接收到java-script文件中的index.html变量中。

有人可以帮我吗? 以下代码是文件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})

1 个答案:

答案 0 :(得分:1)

以下是为您提供概念验证的应用程序:


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

运行该应用程序时,您将获得如下页面:
home page

输入文本并单击计算时,结果将打印到<pre>
results

您如何使用JSON响应由您决定,这里我只是按原样显示它。