Dropzone.js 阻止 Flask 渲染模板

Dropzone.js prevents Flask from rendering template

我正在使用 Dropzone.js 允许通过 Flask 网站拖放上传 CSV 文件。上传过程效果很好。我将上传的文件保存到我指定的文件夹,然后可以使用 df.to_html()dataframe 转换为 HTML 代码,然后将其传递给我的模板。它在代码中到达了那个点,但它不呈现模板并且没有抛出任何错误。所以我的问题是为什么 Dropzone.js 阻止渲染发生?

我也试过 return 来自 table 的 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>

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

Dropzone 将上传您拖放到浏览器中的文件 'in the background'。 它将使用来自服务器的响应并保持页面原样。它使用服务器的响应来判断上传是否成功。

要查看实际效果:

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

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

要真正看到呈现的 complete.html,您需要添加另一个烧瓶端点并找到导航到该端点的方法。

例如: 在 upload1.html 添加:

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

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)

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


Dropzone.js 使用 AJAX 到 post 数据 ,这就是为什么它不会将控制权交还给您的视图函数。

当所有文件都完成上传时,有两种重定向(或呈现模板)的方法。

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

    <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>
    

在视图函数中,添加一条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')

如果您使用的是 Flask-Dropzone,那么:

{{ dropzone.config(redirect_url=url_for('endpoint',foo=bar)) }}