python - 表单提交后在同一页面上输出数据
问题描述
所以我创建了一个小烧瓶程序,它将获取一个文件,进行一些处理并使用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
解决方案
您可能不需要 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?
推荐阅读
- sql - 避免从一列重复
- scala - 加特林测试的模块化
- linux - 如何检查 shell 脚本中的系统参数?
- object-detection - 使用暗网预训练的 .cfg、.weights 文件进行自定义对象检测的 Yolo 算法
- python-3.x - 控制哪个python版本`sudo apt-get install`安装包
- c++ - 我必须定义两个与类相关的函数
- google-data-studio - 如何在 Google Data Studio 中使用“mmmm d, YYYY h:M a”格式解析日期
- angular - 在 Angular 中绘制数据显示问题
- javafx - 避免 FileChooser 反复打开
- azure-cosmosdb - Cosmos DB 抛出输入内容无效,因为所需的属性 - 'id; ' - 缺少错误