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.
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)
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.
Here's a working example:
upload.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
Result after uploading dummy.csv
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With