I am not sure if I am doing this correctly. I have a list of csv files generated by dump from another script in a directly. I am trying to list files, then if name is clicked, allow downloading the file, if a report link next to the name is clicked, render in html table.
Here is what I came up so far.
from flask import Flask, render_template, send_file
import tablib
import os
app = Flask (__name__)
@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
BASE_DIR = '/data/reports/'
abs_path = os.path.join(BASE_DIR, req_path)
# If does not exit
if not os.path.exists(abs_path):
return "Not Found!"
# If file exists
if os.path.isfile(abs_path):
return send_file(abs_path)
# List files
files = os.listdir(abs_path)
return render_template('files.html', files=files)
# Render data in html
@app.route('/report/', defaults={'req_file': ''})
@app.route('/<req_file>')
def index(req_file):
dataset = tablib.Dataset()
with open(req_file) as f:
dataset.csv = f.read()
data = dataset.html
return render_template('index.html', data=data)
In files.html, I have the following template.
<!DOCTYPE html>
<html>
<head>
<title>Available Reports</title>
</head>
<body>
<ul>
{% for file in files %}
<li><a href="{{ file }}">{{ file }}</a> - <a href="/report/">Report</a></li>
{% endfor %}
</ul>
</body>
</html>
In index.html, the following template.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/reportstyle.css') }}"/>
<title>Report</title>
</head>
<body>
<div class="tftable">
{% block body %}
{{ data|safe }}
{% endblock %}
</div>
</body>
</html>
Testing each separately, work as expected, but I can't get flask to render the csv file when clicked from the list.