Flask-Uploads 不会强制只允许 .csv 文件

Flask-Uploads will not enforce allowing only .csv files

我正在使用 Flask、Flask-Bootstrap 和 Flask-Uploads with Python 3.7.1 创建一个非常简单的应用程序,它接受包含原始数据的 csv 文件。

'upload' 页面必须只允许上传 .csv 文件。我已尝试实施 this post.

上给出的答案

使用 .csv 上传尝试按预期工作,但其他文件类型(例如 .jpg)似乎仍被接受。我在这里遗漏了一些明显的东西吗?

'details.html' 现在只是在页面上呈现文件名。

Python代码:

import os  
from flask import Flask, render_template, url_for, request
from flask_bootstrap import Bootstrap
from flask_uploads import UploadSet, configure_uploads

app = Flask(__name__)
Bootstrap(app)

# Upload files configuration
csv_file = UploadSet('files', ('csv'))
app.config['UPLOADED_FILES_DEST'] = 'static/uploadstorage'
configure_uploads(app, csv_file)

# index
@app.route('/')
def index():
    return render_template('index.html')

# if csv file, show the data in a table. if not csv file, reload index page
@app.route('/datauploads', methods=['GET', 'POST'])
def datauploads():

    if request.method == 'POST' and 'csv_data' in request.files:

        file = request.files['csv_data']
        filename = file.filename
        file.save(os.path.join('static/uploadstorage', filename))
        return render_template('details.html', filename=filename)

    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

您在接受文件时忽略了上传集。您需要使用 UploadSet.save() method 进行扩展检查才能启动。

你还需要传入一个扩展序列,目前你传入的是一个字符串,加上一个逗号,使它成为一个元组:

csv_file = UploadSet('files', ('csv',))

并且在您看来使用:

@app.route('/datauploads', methods=['GET', 'POST'])
def datauploads():
    if request.method == 'POST' and 'csv_data' in request.files:
        filename = csv_file.save(request.files['csv_data'])
        return render_template('details.html', filename=filename)

    return render_template('index.html')

您可能想捕获 UploadNotAllowed 异常,否则会出现 500 错误:

from flask_uploads import UploadSet, configure_uploads, UploadNotAllowed
from flask import flash

@app.route('/datauploads', methods=['GET', 'POST'])
def datauploads():
    if request.method == 'POST' and 'csv_data' in request.files:
        try:
            filename = csv_file.save(request.files['csv_data'])
            return render_template('details.html', filename=filename)
        except UploadNotAllowed:
            flash('Only CSV files can be uploaded, please correct', 'error')

    return render_template('index.html')

我使用了 message flashing (which Flask-Bootstrap can support directly),但您的 index.html 也可以更改为接受错误消息。