Dropzone.js阻止Flask呈现模板

use*_*044 11 javascript python flask python-2.7 dropzone.js

我正在使用Dropzone.js允许CSV通过Flask网站拖放文件上传.上传过程非常有效.我将上传的文件保存到我指定的文件夹,然后可以df.to_html()用来转换dataframeHTML代码,然后传递给我的模板.它到达代码中的那一点,但它不呈现模板并且不会抛出任何错误.所以我的问题是为什么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)
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

编辑

以下是csv我上传的示例数据:

Person,Count
A,10
B,12
C,13
Run Code Online (Sandbox Code Playgroud)

Complete.html

<html>

<body>

{{table | safe }}

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Jer*_*len 5

你的代码确实有效.您的模板将被渲染并返回.

Dropzone将上传您在后台拖放到浏览器中的文件. 它将使用服务器的响应并保持页面不变.它使用服务器的响应来了解上传是否成功.

要看到这个:

  • 导航到您的页面
  • 打开你最喜欢的浏览器开发工具; (在Firefox中按CTRL + SHIFT + K)
  • 选择网络选项卡
  • 将csv拖到dropzone窗格中,并注意该请求显示在dev工具网络表中

这是我浏览器的屏幕截图.我从您的问题中复制了您的代码.

代码工作的屏幕截图

要实际看到渲染,complete.html您需要添加另一个烧瓶端点,并有办法导航到该端点.

例如:upload1.html添加:

<a href="{{ url_for('upload_complete') }}">Click here when you have finished uploading</a>
Run Code Online (Sandbox Code Playgroud)

init.py变化和添加:

def upload():

    ...

        # you do not need to read_csv in upload()
        #upload the file
        #df = pd.read_csv(destination)
        #table += df.to_html()

    return "OK"
    # simply returning HTTP 200 is enough for dropzone to treat it as successful
    # return render_template('complete.html', table=table)

# add the new upload_complete endpoint
# this is for example only, it is not suitable for production use
@app.route('/upload-complete')
def upload_complete():
    target = os.path.join(APP_ROOT, 'uploads/')
    table=""
    for file_name in os.listdir(target):
        df = pd.read_csv(file_name)
        table += df.to_html()
    return render_template('complete.html', table=table)
Run Code Online (Sandbox Code Playgroud)


Gre*_* Li 5

更新:现在您可以使用Flask-Dropzone,这是一个将Dropzone.js与Flask集成的Flask扩展。对于此问题,您可以将其设置DROPZONE_REDIRECT_VIEW为要在上传完成时重定向的视图。


Dropzone.js使用AJAX来发布数据,这就是为什么它不会将控件交还给您的视图函数的原因。

完成所有文件上传后,有两种方法可以重定向(或渲染模板)。

  • 您可以添加一个按钮来重定向。

    <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>
    
    Run Code Online (Sandbox Code Playgroud)

在视图函数中,添加一条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')
Run Code Online (Sandbox Code Playgroud)