【问题标题】:Flask and HTML: Redirect json response to be displayed at the bottom of the same page instead showing response on a separate pageFlask 和 HTML:重定向 json 响应以显示在同一页面的底部,而不是在单独的页面上显示响应
【发布时间】:2018-10-01 11:50:29
【问题描述】:

Web 开发的超级新手。我正在使用 Flask 部署一个 sklearn 机器学习模型。

我能够正确地以 JSON 格式返回响应预测,但它显示在单独的页面上。我想更改我的 HTML 和 Flask app.py,使预测响应出现在 HTML 中 form 底部的一个新创建的容器元素中

这是我的index.html

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href= "{{ url_for('static',filename='css/style.css') }}">


</head>
<body>
<div class = 'intro'>
  This is a simple website that hosts a Machine Learning model trained using <i>sklearn</i> to predict one of three authors:
  <b>HP Lovecraft</b>, <b>Edgar Allan Poe</b> and <b>Mary Shelley</b>. Simply enter a passage of one of those three authors and you will get a prediction.


</div>

<div class="authorimage">
  <div class="row">
  <div class="column">
    <h2>Mary Shelley</h2>
    <p><img src = "{{ url_for('static',filename='img/mary.jpeg') }}"></p>
  </div>
  <div class="column">
    <h2>H.P Lovecraft</h2>

    <p><img src = "{{ url_for('static',filename='img/lovecraft.jpeg') }}"></p>
  </div>
  <div class="column">
    <h2>Edgar Allan Poe</h2>
    <p><img src = "{{ url_for('static',filename='img/eap.jpeg') }}"></p>
  </div>
</div>


</div>


<div class = 'input'>
  <form action="/api" method="POST">
    <textarea name = "passage_input" cols="35" wrap="soft"></textarea>
    <input type="submit">
</form>
</div>


<div class = "prediction">
Not sure how to collect the response from app.py into a box here..
</div>

</body>
</html>

这是我的app.py

import numpy as np
import pandas as pd
from flask import Flask, render_template, abort, jsonify, request
import pickle
from vectorspace import VectorSpace
import json

with open('/Users/abhishekbabuji/Desktop/spooky_author_model.pkl', 'rb') as fid:
     pkl_model_loaded = pickle.load(fid)


app = Flask(__name__, static_url_path='')

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


@app.route('/api', methods = ['POST'])
def predict():
  text_input = request.form['passage_input']
  return parse(pd.Series([text_input]))

def parse(input_passage):

    reduction_type = 'lemmatize'
    trans_input_passage = VectorSpace(input_passage, reduction = reduction_type).apply_reduction()


    return json.dumps(pkl_model_loaded.predict(trans_input_passage)[0])




if __name__ == '__main__':
  app.run(port = 9000, debug = True)

【问题讨论】:

  • 不知道为什么会有反对票..

标签: python html python-3.x flask response


【解决方案1】:

你必须使用jquery来动态更新页面:

<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href= "{{ url_for('static',filename='css/style.css') }}">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
 <body>
   ...
 <div class = 'input_wrapper'>
    <textarea name = "passage_input" cols="35" wrap="soft" class="paragraph"></textarea>
    <button class='predict'>Predict</button>
 </form>
 </div>
<div class = "prediction"></div>
</body>
<script> 
$(document).ready(function(){
   $('.input_wrapper').on('click', '.predict', function(){
      var data = $('.paragraph').val();
      $.ajax({
       url: "/api",
      type: "get",
      data: {text:data},
      success: function(response) {
        $(".prediction").html(response.name);
       }
    });
   });
});
</script>
</html>

在应用中:

@app.route('/api')
def predict():
  text_input = request.args.get('text')
  return flask.jsonify({'name':parse(pd.Series([text_input]))})

现在,当点击“预测”按钮时,javascript 会从textarea 获取输入的文本,并动态调用路由'/api' 并使用结果更新prediction div。

【讨论】:

    【解决方案2】:

    您可以在 jinja 中使用 for 将您的 json 结果解析为 html,例如:

    {% for key, value in results %}        
      <span>{{key}} : {{value}}</span>
    {% endfor %}
    

    在你的烧瓶应用中:

    return render_template("index.html", results = your result)
    

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 2016-07-28
      • 2020-06-09
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多