I have created a Flask app that creates a list and returns the list to an HTML page. I would also like to make the list downloadable as a CSV file.
So far I understand how to do these tasks as separate functions.
Is there a way to combine these functions into one so that a list is created only once, displaying the data on an HTML template, and also providing a download link?
Please view the basic examples below:
from flask import Flask, render_template, Response, url_for
app = Flask(__name__)
@app.route('/')
def hello_world():
fruits = ['apple', 'pear', 'banana', 'grapes', 'mango']
return render_template('fruit.html', fruit=fruits)
@app.route('/fruits.csv')
def generate_fruit_file():
def generate():
fruits = ['apple', 'pear', 'banana', 'grapes', 'mango']
for f in fruits:
yield ''.join(f) + '\n'
return Response(generate(), mimetype='text/csv')
if __name__ == '__main__':
app.run(debug=True)
HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{% for f in fruit %}
<ul>
<li style="display: block;">{{ f }}</li>
</ul>
{% endfor %}
<a href="{{'/fruits.csv'}}">get file</a>
</body>
</html>