将 werkzeug.datastructures.FileStorage 转换为 flask 后端的列表列表

Convert werkzeug.datastructures.FileStorage to list of lists for flask backend

使用 flask 后端,正在将一个 csv 文件上传到服务器,其中包含以下 html。

<form method="POST" enctype="multipart/form-data" action="/csvUpload">
                  <input type="file" id="myFile" name="filename" accept=".csv">
                  <input type="submit">
 </form>

在flask的routes.html上,我们有如下函数,

@app.route('/csvUpload', methods=['POST'])
def csvUpload():
    try:
        if request.method == 'POST':
            if request.files:
                uploaded_file = request.files['filename']
                data = uploaded_file.stream.read() # This line uses the same variable and worked fine
                #Convert the FileStorage to list of lists here.
                return data
    except Exception as e:
        traceback.print_exc()
        return "Alas! The code didnt work."

所需的输出类似于csv.reader(file, 'r')的输出,当从具有静态路径的本地系统读取文件时。这样做的原因是我想使用这个 csv 来更新附加在后端的数据库中的表。

尝试以下使用 io.StringIO 模块的方法:

@app.route('/csvUpload', methods=['POST'])
def csvUpload():
    if request.method == 'POST':
        if request.files:
            uploaded_file = request.files['filename']
            data = uploaded_file.stream.read() # This line uses the same variable and worked fine
            #Convert the FileStorage to list of lists here.

            stream = io.StringIO(data.decode("UTF8"), newline=None)
            reader = csv.reader(stream)
            for row in reader:
                print(', '.join(row)) 

            return data

一些测试数据returns以下上传到终端:

Name, Age
Kevin, 15
Perry, 14
Paul, 30

这段代码应该可以让你实现你想要的。