繁体   English   中英

将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

一些测试数据在上传时向终端返回以下内容:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM