我正在使用 Dropzone.js
允许通过 Flask
网站拖放上传 CSV
文件。上传过程效果很好。我将上传的文件保存到我指定的文件夹,然后可以使用 df.to_html()
将 dataframe
转换为 HTML
代码,然后我传递给我的模板。它在代码中到达了那个点,但它不呈现模板并且没有抛出任何错误。所以我的问题是为什么 Dropzone.js
阻止渲染发生?
我也试过只从表中返回 HTML
代码而不使用 render_template
,但这也不起作用。
初始化.py
import os
from flask import Flask, render_template, request
import pandas as pd
app = Flask(__name__)
# get the current folder
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
@app.route('/')
def index():
return render_template('upload1.html')
@app.route('/upload', methods=['POST'])
def upload():
# set the target save path
target = os.path.join(APP_ROOT, 'uploads/')
# loop over files since we allow multiple files
for file in request.files.getlist("file"):
# get the filename
filename = file.filename
# combine filename and path
destination = "/".join([target, filename])
# save the file
file.save(destination)
#upload the file
df = pd.read_csv(destination)
table += df.to_html()
return render_template('complete.html', table=table)
if __name__ == '__main__':
app.run(port=4555, debug=True)
上传1.html
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">
<table width="500">
<tr>
<td>
<form action="{{ url_for('upload') }}", method="POST" class="dropzone"></form>
</td>
</tr>
</table>
编辑
这是我正在上传的示例 csv
数据:
Person,Count
A,10
B,12
C,13
完整.html
<html>
<body>
{{table | safe }}
</body>
</html>
最佳答案
更新:现在您可以使用Flask-Dropzone ,一个将 Dropzone.js 与 Flask 集成的 Flask 扩展。对于这个问题,你可以设置DROPZONE_REDIRECT_VIEW
到上传完成后要重定向的 View 。
Dropzone.js 使用 AJAX 发布数据,这就是它不会将控制权交还给您的 View 函数的原因。
当所有文件都完成上传时,有两种重定向(或渲染模板)的方法。
您可以添加一个按钮进行重定向。
<a href="{{ url_for('upload') }}">Upload Complete</a>
您可以将事件监听器添加到自动重定向页面(使用 jQuery)。
<script> Dropzone.autoDiscover = false; $(function() { var myDropzone = new Dropzone("#my-dropzone"); myDropzone.on("queuecomplete", function(file) { // Called when all files in the queue finish uploading. window.location = "{{ url_for('upload') }}"; }); }) </script>
在 View 函数中,添加一个if
检查 HTTP 方法是否为 POST
的语句:
import os
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['UPLOADED_PATH'] = 'the/path/to/upload'
@app.route('/')
def index():
# render upload page
return render_template('index.html')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
for f in request.files.getlist('file'):
f.save(os.path.join('the/path/to/upload', f.filename))
return render_template('your template to render')
关于javascript - Dropzone.js 阻止 Flask 渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42101786/