【问题标题】:Convert werkzeug.datastructures.FileStorage to list of lists for flask backend将 werkzeug.datastructures.FileStorage 转换为烧瓶后端的列表列表
【发布时间】:2021-06-22 10:21:43
【问题描述】:

使用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 来更新与后端连接的数据库中的表。

【问题讨论】:

  • 您是否尝试过像csv.reader(data) 那样将data 传递给csv.reader
  • 是的,我有。之后,当我遍历 csv 阅读器对象时,出现以下错误。对于温度:_csv.Error: iterator should return strings, not int (did you open the file in text mode?)

标签: python python-3.x csv file-storage


【解决方案1】:

尝试以下使用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

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

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多