Upload and Display CSV file in html table Flask Python

To develop any Machine Learning web application data is must required. in this post, I will show you how to upload and display CSV files in HTML table Flask. By reading this post you will also be able to understand how to upload and read excel file in python flask. Both are similar.

Note: If you are new in Flask I have written some basic tutorial for Flask you can definately read those out.

Must Read:

I will divide this tutorial into two parts:

  1. Part1: Read and display csv file in flask
  2. Part2: Upload and Display CSV file in Flask

Read and Display CSV file in Python Flask

In this section, we will read a CSV file inside our Flask code and display that CSV file on web page as HTML table. The CSV file can be any file stored in your computer.

We want to have a button on our index HTML page (index_read_and_show_data.html). If we click that button the CSV file should show on a different page (show_data.html).

index_read_and_show_data.html (index page)

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Flask GET, POST tutorial</h1>
    <p>Display csv file in html table Flask</p>
    <form action="/show_data" target="_blank">
    <input type="submit" value="Show CSV" />
    </form>
  </body>
</html>
read excel file in python flask

Here in this index HTML code:

  • Line 10: In home page of our Flask application we are creating a submit button named “Show CSV
  • If we click this button a new page will open named 127.0.0.1:5000/show_data

Now let’s write our Flask backend code:

flask_get_post_read_csv.py

from flask import Flask, render_template
import pandas as pd

#*** Backend operation
# Read csv file in python_ flask
df = pd.read_csv('data/comment.csv')

# Read excel file in python_ flask
# df = pd.read_excel('data/comment.xlsx')

# WSGI Application
# Configure template folder name
# The default folder name should be "templates" else need to mention custom folder name for template path
# The default folder name for static files should be "static" else need to mention custom folder for static path
app = Flask(__name__, template_folder='templateFiles', static_folder='staticFiles')

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

@app.route('/show_data',  methods=("POST", "GET"))
def showData():
    # Convert pandas dataframe to html table flask
    df_html = df.to_html()
    return render_template('show_csv_data.html', data=df_html)

if __name__=='__main__':
    app.run(debug = True)

Here in this code:

  • line 6: We are reading the csv file which we are going to display in web page
  • line 9: Commented, you can use this line if you want to read excel file instead of CSV
  • line 15: Configuring Flask back end for custom template and static path
  • line 19: Loading “index_read_and_show_data.html” as homepage [@app.route('/')]
  • Line 24: Converting pandas dataframe to html table. If you are not converting, your CSV data will display as string not as a html table
  • Line 25: Display converted data to 127.0.0.1:5000/show_data [@app.route('/show_data',  methods=("POST", "GET"))] with html file named “show_csv_data.html
Also Read:  Getting Started with Django with Python - Easy Tutorial

In line 25 we are storing our converted HTML table in a variable named “data_var“. So now we need to create an HTML file named “show_csv_data.html“, where we need to call that “data_var” variable to display our CSV file (converted HTML table) [return render_template(‘show_csv_data.html’, data=df_html)].

show_csv_data.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Flask GET, POST tutorial</h1>
    <p>Display csv file in html table Flask</p>

{{ data_var|safe }}

    </body>
</html>

In this HTML code at line 10, we are calling that “data_var” variable to display our data. Note: This is the way of Jinja Template to communicate between backend and frontend codes.

Read and display csv file in flask
Final Output at Browser

Upload and Display CSV file in Flask

In part 1 we just read one CSV file from our local directory. If we want to use different data, we have to change inside Flask code(pd.read_csv()/ pd.read_excel()). This is not the correct way while making and Web application. Our web page must support the upload data feature.

Now let’s list down what we want to achieve with this web app:

  • Uploading feature in front end
  • Once data is uploaded successfully it should show the message
  • Must have separate button, once clicked CSV data shoud show as a html table in different page

So now let’s create home page of our Flask application. I am naming this HTML file as “index_upload_and_show_data.html

index_upload_and_show_data.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Flask GET, POST tutorial</h1>
    <p>Show CSV file in html using FLASK</p>

    <form method="POST" enctype="multipart/form-data" action="/">
        <input type="file" id="myFile" name="uploaded-file" accept=".csv">
        <input type="submit" value="Upload file">
    </form>
  <br>
  <p style="color:blue;">Choose csv file to upload</p>
  <form action="/show_data" target="_blank">
        <input type="submit" value="Show CSV" />
    </form>
  </body>
</html>

Here in this code:

  • Line 10 – line 13: we are adding data upload form functionality
  • Line16 – line18: we are adding a button to show data in different page (http://127.0.0.1:5000/show_data)
  • Line 15: Adding a string “Choose csv file to upload” in blue color, it should change to green color once data is uploaded successfully
flask upload csv pandas page1

Now if you upload any data and click button “Upload file” the message “Choose csv file to upload” should change to “file uploaded successfully” in green color. To do this we need to write another HTML file. I am naming this HTML file as “index_upload_and_show_data_page2.html

index_upload_and_show_data_page2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Flask GET, POST tutorial</h1>
    <p>Show CSV file in html using FLASK</p>

    <form method="POST" enctype="multipart/form-data" action="/">
        <input type="file" id="myFile" name="uploaded-file" accept=".csv">
        <input type="submit" value="Upload file">
    </form>
  <br>
  <p style="color:green;">file uploaded successfully</p>
  <form action="/show_data" target="_blank">
        <input type="submit" value="Show CSV" />
    </form>
  </body>
</html>

Here in this code every line is same as “index_upload_and_show_data.html” except line 15 where we are changing message to “file uploaded successfully”

Also Read:  How to Create Desktop Application Using Python

Note: In line 11 I have mentioned accepted file = CSV you can change it to .xlsx, if you want to upload and read excel file in python flask

flask upload csv pandas page2

Now that we are done with our two home pages, let’s write our Flask backend code I am naming this code as “flask_get_post_upload_read_csv.py“:

flask_get_post_upload_read_csv.py

from flask import Flask, render_template, request, session
import pandas as pd
import os
from werkzeug.utils import secure_filename

#*** Flask configuration

# Define folder to save uploaded files to process further
UPLOAD_FOLDER = os.path.join('staticFiles', 'uploads')

# Define allowed files (for this example I want only csv file)
ALLOWED_EXTENSIONS = {'csv'}

app = Flask(__name__, template_folder='templateFiles', static_folder='staticFiles')
# Configure upload file path flask
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Define secret key to enable session
app.secret_key = 'This is your secret key to utilize session in Flask'


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

@app.route('/',  methods=("POST", "GET"))
def uploadFile():
    if request.method == 'POST':
        # upload file flask
        uploaded_df = request.files['uploaded-file']

        # Extracting uploaded data file name
        data_filename = secure_filename(uploaded_df.filename)

        # flask upload file to database (defined uploaded folder in static path)
        uploaded_df.save(os.path.join(app.config['UPLOAD_FOLDER'], data_filename))

        # Storing uploaded file path in flask session
        session['uploaded_data_file_path'] = os.path.join(app.config['UPLOAD_FOLDER'], data_filename)

        return render_template('index_upload_and_show_data_page2.html')

@app.route('/show_data')
def showData():
    # Retrieving uploaded file path from session
    data_file_path = session.get('uploaded_data_file_path', None)

    # read csv file in python flask (reading uploaded csv file from uploaded server location)
    uploaded_df = pd.read_csv(data_file_path)

    # pandas dataframe to html table flask
    uploaded_df_html = uploaded_df.to_html()
    return render_template('show_csv_data.html', data_var = uploaded_df_html)

if __name__=='__main__':
    app.run(debug = True)

Here in this code:

  • Line 9: Defining the folder path, where you will save the uploaded CSV file to process further
  • Line 12: I have mentioned allowed file format to CSV, you can change it to ‘xlsx’ if you want to upload and read excel file in python flask
  • Line 16: Configuring Flask for the upload directiory
  • Line 19: Setting secret key to enable Flask session. If you are not defining the secret key you may get error “RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.”
  • Line 22-24: Loading “index_upload_and_show_data.html” as home page (http://127.0.0.1:5000/)
  • Line 30: Fetching uploaded data from frontend(HTML page) with ID “uploaded-file” (line 12 in both index_upload_and_show_data.html and index_upload_and_show_data_page2.html)
  • Line 33: Extracting uploaded data name, we will save uploaded CSV file in our local directory with the same name
  • Line 36: Save uploaded data in upload directory (Line 16) with the same name
  • Line 39: Storing full path in Uploaded directory in session. We will use this path while reading this uploaded data in another function
  • Line 41: Loading index_upload_and_show_data_page2.html in home page to show message if data is uploaded successfully
  • Line 46: Retriving uploaded file path from session
  • Line 49: Since we know the full file path of the uploaded data, now we can read this csv file using pandas
  • Line 52: To display csv file as table in HTML, we need to convert this pandas dataframe to html table
  • Line 53: Showing HTML table (converted CSV data) in “show_csv_data.html”. Note the page location to display the data would be “127.0.0.1:5000/show_data” as per line 43 [@app.route(‘/show_data’)]
Also Read:  Build Question Answering API with Flask and Python

In line 53 we are storing our converted HTML table in a variable named “data_var“. So now we need to create an HTML file named “show_csv_data.html“, where we need to call that “data_var” variable to display our CSV file (converted HTML table).

Before running our Flask code we need to create upload folder as mentioned in line 9. I am creating a folder named “uploads” inside our static folder “staticFiles”. You create the folder with any name.

show_csv_data.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Flask GET, POST tutorial</h1>
    <p>Display csv file in html table Flask</p>

{{ data_var|safe }}

    </body>
</html>

Now let’s run our Flask code “flask_get_post_upload_read_csv.py” to see the final output in browser

Upload and display csv file in html

Conclusion

In this post I have shown you how you can Upload and Display CSV file in html table Flask Python. By reading this post you can also upload and read excel file in python flask.

In this post I have given you a starting point, how you can use session to store any variable or data path in some function and retrive that path in different function.

I have also shown you how you can use Flask GET POST method to upload and display csv file on web page developed by Flask with Python.

If you have any question or suggestion regarding this post please let me know in the comment section below

1 thought on “Upload and Display CSV file in html table Flask Python”

  1. Hello! Very useful article.

    I have a quick question. If I want to save to the local folder a .json file, what changes should I make?

    Reply

Leave a comment