简体   繁体   English

使用 Flask 上传和读取 CSV 文件

[英]Uploading and reading a CSV file with Flask

I'm currently in the process of making a program to upload and read csv files.我目前正在制作一个程序来上传和读取 csv 文件。 I'm throwing a key error when submitting a file to be uploaded and can't really seem to figure out why and was hoping for some help.我在提交要上传的文件时抛出了一个关键错误,并且似乎无法弄清楚原因并希望得到一些帮助。 It uploaded and saved the file before I tried adding the read file functionality but after that, it started having issues.在我尝试添加读取文件功能之前,它上传并保存了文件,但在那之后,它开始出现问题。 The error is saying that 'filename' is a key error even though it seemed to work fine before I tried reading the file.错误是说“文件名”是一个关键错误,即使在我尝试读取文件之前它似乎工作正常。 Help or leading me down the right path would be greatly appreciated.帮助或引导我走上正确的道路将不胜感激。 Thanks so much!非常感谢!

Views.py视图.py

from flask import render_template, request, redirect
from app import app
import os
import csv


@app.route('/', methods=["GET", "POST"])
def index():
    data = []
    if request.method == 'POST':
        if request.files:
            uploaded_file = request.files['filename'] # This line uses the same variable and worked fine
            uploaded_file.save(os.path.join(app.config['FILE_UPLOADS'], uploaded_file.filename))
            f = request.form['filename'] # This is the line throwing the error
            with open(f) as file:
                csv_file = csv.reader(file)
                for row in csv_file:
                    data.append(row)
            return redirect(request.url)
    return render_template('index.html', data=data)


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

app.config['FILE_UPLOADS'] = "C:\\Users\\Zachary\\Documents\\VSCode_Projects\\monday_webapp\\app\\static\\file\\uploads"

Index.html索引.html

{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block body %}

<div class="jumbotron">
    <h1 style='text-align: center'>Zach's Web Application</h1>
</div>
<div>
    <p class="lead">Upload a csv file to view its data.</p>
    <form method="POST" enctype="multipart/form-data" action="/">
        <input type="file" id="myFile" name="filename" accept=".csv">
        <input type="submit">
    </form>
</div>
<div>
    {{ data }}
</div>
<div>

{% endblock %}

In flask request.form["input_name"] is used to get the input data, but not for input type=files which are accesible through request.files["input_name"] , always using enctype=multipart/form-data in the form.在 flask request.form["input_name"]用于获取输入数据,但不适用于可通过request.files["input_name"]访问的 input type=files ,始终使用enctype=multipart/form-data形式. You can get more info in the oficial documentation: https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/您可以在官方文档中获得更多信息: https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

On the other hand, request.files['filename'] is a FileStorage type, the function open(f) expects str, bytes or os.PathLike object, not FileStorage .另一方面, request.files['filename']是 FileStorage 类型, function open(f)需要str、bytes 或 os.PathLike object,而不是 FileStorage

The following code should works:以下代码应该可以工作:

from flask import render_template, request, redirect
from app import app
import os
import csv


@app.route('/', methods=["GET", "POST"])
def index():
    data = []
    if request.method == 'POST':
        if request.files:
            uploaded_file = request.files['filename'] # This line uses the same variable and worked fine
            filepath = os.path.join(app.config['FILE_UPLOADS'], uploaded_file.filename)
            uploaded_file.save(filepath)
            with open(filepath) as file:
                csv_file = csv.reader(file)
                for row in csv_file:
                    data.append(row)
            return redirect(request.url)
    return render_template('index.html', data=data)


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

app.config['FILE_UPLOADS'] = "C:\\Users\\Zachary\\Documents\\VSCode_Projects\\monday_webapp\\app\\static\\file\\uploads"

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

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