8

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)

1 Answer 1

12

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:
enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @kchomski, I have another object like {{shape}} say {{columns}} which is df.columns, which I want to display after the if loop runs and displays shape , along with the 2nd return but the loop stops at the 1st return after the if condition satisfies. How can I get what I want?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.