如何将 excel 或 csv 文件作为 Pandas 数据框上传到烧瓶?

Man*_*nth 6 python flask pandas

我一直在尝试在烧瓶应用程序上上传一个 csv/excel 文件作为熊猫数据框。我找不到任何可以帮助将文件上传为数据框的方法。下面是使用的代码。

from flask import Flask, request, render_template
from werkzeug import secure_filename
import pandas as pd
app = Flask(__name__)

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

@app.route('/uploader',methods = ['GET','POST'])
def uploader():
    if request.method == 'POST':
        #f = request.files['file']
        df = pd.read_csv(request.files.get('file'))
        #f.save(secure_filename(f.filename))
        #df = pd.DataFrame(eval(f))
        return print(df.shape)

if __name__ == '__main__':
    app.run(debug = True)
Run Code Online (Sandbox Code Playgroud)

kch*_*ski 9

您没有提供在代码 ( upload.html) 中使用的模板。
return print(...)返回None并且None不是来自 Flask 视图的有效响应。

这是一个工作示例:

上传.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method=post enctype=multipart/form-data>
    <input type=file name=file>
    <input type=submit value=Upload>
</form>
Shape is: {{ shape }}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

应用程序

from flask import Flask, request, render_template
import pandas as pd

app = Flask(__name__)

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        df = pd.read_csv(request.files.get('file'))
        return render_template('upload.html', shape=df.shape)
    return render_template('upload.html')

if __name__ == '__main__':
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

虚拟文件

id,name,surname
1,John,Doe
2,Jane,Doe
Run Code Online (Sandbox Code Playgroud)

上传后的结果dummy.csv
在此处输入图片说明