【问题标题】:Flask assign CSV file contents to memory and display the content on HTML pageFlask 将 CSV 文件内容分配到内存并在 HTML 页面上显示内容
【发布时间】:2018-05-10 07:47:24
【问题描述】:

我正在尝试构建一个烧瓶应用程序,它会加载一个 csv 文件,将其分配给内存,然后在 HTML 页面上显示内容,

我使用的代码如下,当我运行代码并尝试加载文件时,出现以下错误,

AttributeError: '_io.BytesIO' 对象没有属性 'file

烧瓶

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            ## snippet to read code below
            file.stream.seek(0) # seek to the beginning of file
            myfile = file.file # will point to tempfile itself
            dataframe = pd.read_csv(myfile)
            ## end snippet

            return "yatta"
        else:
            return "file not allowed"

    return render_template("upload.html")

HTML

<div class="form-group">
    <form method="POST" enctype=multipart/form-data>
    <input class="btn btn-sm btn-primary" type="file" name="file">
    <input type="submit" value='upload'>
</div>
<table border="1" cellpadding="5" cellspacing="5">
            {% for row in data %}
                <tr>
                {% for d in row %}
                    <td>{{ d }}</td>
                {% endfor %}
            </tr>
            {% endfor %}
        </table>

【问题讨论】:

标签: python flask


【解决方案1】:

这个具体的实现我不熟悉,但是既然你用的是file.stream.seek(0),我觉得

myfile = file.stream

将部分解决您的问题。

虽然部分?因为您的流是字节流 - 如果您使用的是 Python3,pandas.read_csv 需要文本文件/流 - 即 unicode。

我使用这个转换来解决问题

unicode_stream = io.StringIO(download_stream.getvalue().decode())

【讨论】:

  • 谢谢你,我按照你的建议尝试了,unicode_stream = io.StringIO(download_stream.getvalue().decode())myfile = unicode_stream.read(request.files['file'])csvfile = csv.DictReader(myfile) 当我尝试这个时,我得到“NameError: name 'download_stream' is not defined”错误
  • 这只是我代码中的一个引用 - download_steam 属于 io.ByresIO 类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多