我一直在尝试制作一个基本的烧瓶应用程序。我在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})
答案 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>
您如何使用JSON响应由您决定,这里我只是按原样显示它。