如何将 excel 或 csv 文件作为 Pandas 数据框上传到烧瓶?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51356402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload excel or csv file to flask as a Pandas data frame?
提问by Manju Savanth
I have been trying to upload a csv/excel file as pandas data frame on a flask application. I am not able to find any method which could help upload the file as a data frame. Below is the code used.
我一直在尝试在烧瓶应用程序上上传一个 csv/excel 文件作为Pandas数据框。我找不到任何可以帮助将文件上传为数据框的方法。下面是使用的代码。
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)
回答by kchomski
You didn't provide a template you're using in your code (upload.html
).
Also return print(...)
returns None
and None
is not a valid response from a Flask view.
您没有提供在代码 ( upload.html
) 中使用的模板。
也return print(...)
返回None
并且None
不是来自 Flask 视图的有效响应。
Here's a working example:
这是一个工作示例:
upload.html
上传.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>
app.py
应用程序
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)
dummy.csv
虚拟文件
id,name,surname
1,John,Doe
2,Jane,Doe