我使用Dropzone.js允许通过Flask网站拖放CSV文件的上传.上传过程效果很好.我将上传的文件保存到我指定的文件夹,然后可以使用df.to_html()将数据框转换为
HTML代码,然后将其传递给我的模板.它在代码中到达这一点,但它不渲染模板,并且不会抛出任何错误.所以我的问题是为什么Dropzone.js阻止渲染发生?
我也尝试从表中返回HTML代码,而不是使用render_template,但这也不行.
init.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)
upload1.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
Complete.html
<html> <body> {{table | safe }} </body> </html>
解决方法
当所有文件完成上传时,有两种重定向(或渲染模板)的方法.
< a href =“{{url_for('upload')}}”>上传完成< / 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>
在视图函数中,添加一个if语句来检查HTTP方法是否为POST:
import os from flask import Flask,request app = Flask(__name__) app.config['UPLOADED_PATH'] = os.getcwd() + '/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(app.config['UPLOADED_PATH'],f.filename)) return render_template('your template to render')