ArticleZip > Flask Download A Csv File On Clicking A Button Duplicate

Flask Download A Csv File On Clicking A Button Duplicate

When working on a web application with Flask, you might come across a common need to offer users the ability to download data in the form of a CSV file with just a click of a button. This can be particularly useful when you want to provide users with a simple way to export data for further analysis or sharing. In this guide, we will walk you through the steps to implement this feature in your Flask application.

First and foremost, you'll need to have Flask installed in your Python environment. If you haven't already done so, you can easily install Flask using pip:

Bash

pip install Flask

Next, you'll need to create a route in your Flask application that will handle the download functionality. You can create a route like this:

Python

from flask import Flask, Response

app = Flask(__name__)

@app.route('/download-csv')
def download_csv():
    csv_data = "Name,EmailnJohn Doe,[email protected] Smith,[email protected]"
    return Response(
        csv_data,
        mimetype="text/csv",
        headers={"Content-disposition":
                 "attachment; filename=data.csv"}
    )

In the code snippet above, we have defined a route `/download-csv` that returns a CSV file as a response. The `csv_data` variable contains the actual CSV content, which you can dynamically generate based on your application's data.

The `Response` object is used to create the HTTP response. We set the `mimetype` to `"text/csv"` to specify that the content is in CSV format. Additionally, we set the `Content-disposition` header to `"attachment; filename=data.csv"`, which tells the browser to treat the response as a file download with the specified filename.

To trigger the file download when a user clicks a button, you can create a simple HTML template with a button that links to the `/download-csv` route:

Html

<title>Download CSV Example</title>


    <h1>Download CSV File</h1>
    <a href="/download-csv" download><button>Download CSV</button></a>

In the HTML template above, we have a button that links to the `/download-csv` route. The `download` attribute on the anchor tag prompts the browser to download the linked resource rather than navigating to it.

By clicking the "Download CSV" button, users will trigger the download of the CSV file generated by your Flask application.

That's it! You have now successfully implemented a feature in your Flask application that allows users to download a CSV file with just one click of a button. Experiment with different data and customize the functionality to fit your specific needs. Happy coding!

×