因此,我创建了一个小烧瓶程序,该程序将使用yield
来处理文件,进行一些处理并返回数据流。
我正在使用html表单上传和提交文件。表单将文件发送到python脚本并返回输出。问题是由于表单操作属性,输出显示在了不同的页面上,而我需要在同一页面上输出。可能在div
标记内。
index.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
上传输数据。
我尝试将重定向与Response结合使用,但无法说出TypeError: 'generator' object is not callable
答案 0 :(得分:1)
您可能不需要JavaScript即可...
由于需要在“ index.html”页面(即http://localhost:5000)上显示结果,因此需要为同一索引页面创建两条路由。
第一个路由将加载新表单(未设置方法属性),而第二个路由将重新加载流程表单(将方法属性设置为POST)。两条路由都指向同一索引页。
以下是您的代码的外观:-
index.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)
通过此链接了解更多信息:Send data from a textbox into Flask?