首页 > 解决方案 > 表单提交后在同一页面上输出数据

问题描述

所以我创建了一个小烧瓶程序,它将获取一个文件,进行一些处理并使用yield.

我正在使用 html 表单进行文件上传和提交。表单将文件发送到 python 脚本并返回输出。问题是由于表单操作属性,输出显示在不同的页面上,而我需要在同一页面上输出。可能在div标签内。

索引.html

<script>
if (!!window.EventSource) {
  var source = new EventSource('/upload');
  source.onmessage = function(e) {
    console.log(e)
    var byte = e.data;
    var res = byte.split(/\s/);
    console.log(res[0])
    $("#morse").text(res[0].slice(1,));

  }
}
</script>
<form action="/upload" method=post enctype=multipart/form-data >
    <p><input type="file" name="file" >
    <input type="submit" value="Upload" id="search_form_input">
    </form>


<div id="morse" class="info">nothing received yet</div>  // this is where is need my data

Python代码

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

@app.route("/upload", methods=['GET', 'POST'])
def streambyte():
    if request.method == 'POST':
        f = request.files['file']
        list_of_items = unAssign(f)  # some file processing
        def events():
            for i in list_of_items:
                yield "data: %s\n\n" % (i)
            time.sleep(1)  # an artificial delay

        return Response(events(), content_type='text/event-stream')

http://localhost:5000/upload当我需要它时,这会流式传输数据http://localhost:5000

我尝试将重定向与响应一起使用,但它失败了TypeError: 'generator' object is not callable

标签: pythonpython-3.xflask

解决方案


您可能不需要 JavaScript 来执行此操作...

由于您需要“index.html”页面上的结果(即http://localhost:5000),因此您需要为同一个索引页面创建两条路由。

第一个路由将加载新表单(方法属性未设置),而第二个将重新加载流程表单(方法属性设置为 POST)。两条路线都将指向同一个索引页。

下面是您的代码的外观:-

索引.html

<!DOCTYPE html>
<html>
<head>
    <title>Flask App - Output data on same page after form submit</title>
</head>
<body>

    <form method=post enctype=multipart/form-data >
    <p><input type="file" name="file" >
    <input type="submit" value="Upload" id="search_form_input">
    </form>


    <div id="morse" class="info">nothing received yet</div>
    <h3>{{ result }}</h3>
    <h3>{{ file_path }}</h3>


<!-- this is where is need my data -->

</body>
</html>

Python代码

from flask import Flask, render_template, request

app = Flask(__name__)


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


@app.route("/", methods=['GET', 'POST'])
def streambyte():
    # your file processing code is here...
    f = request.files['file']
    your_script_result = 'This variable holds the final data output'
    # your file processing code is here...

    return render_template('index.html', file_path = f, result = your_script_result)


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

从此链接阅读更多内容:将数据从文本框发送到 Flask?


推荐阅读