【发布时间】:2019-04-17 09:30:39
【问题描述】:
所以我创建了一个小烧瓶程序,它将获取一个文件,进行一些处理并使用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 上传输数据。
我尝试将重定向与响应一起使用,但它未能说出 TypeError: 'generator' object is not callable
【问题讨论】:
-
您应该使用 Ajax 来完成这种工作。它将向服务器发送一个异步请求,服务器将返回一个答案,然后使用 Javascript/Jquery 您将修改 DOM 以显示这些新信息。 Check out this link for more info on how to use Ajax with Flask
-
尝试使用 Ajax 或其他替代方法是使用响应对象呈现相同的模板。因此,您首先会执行 render_template('some_html'),然后处理 render_template('some_html', data=data) 并解析数据。
-
@Jessi 我明白了。我使用 ajax 将文件发送到 python。但认为该文件不存在于该发布请求中。我不想存储它。所以一切都需要在该请求中。我正在考虑将这些数据临时存储在泡菜中并删除它
标签: python python-3.x flask