I've created a Heroku web app as a personal project, but keep running into errors, as I'm new to Flask and SQL databases.
I've created a page that displays the database that users input on the website (operates like an admin view). My plan was to have a button/link that exports whatever information is currently in the database's table as CSV.
Here is the HTML which holds the "download CSV" link - the page is 'download_csv.html':
<body>
<h3>Download Power Rankings CSV Report</h3>
<p>
<a href={{ url_for('download_report') }}>Generate CSV Report</a>
</p>
</body>
The route I have created within app.py in regards to both the page with the link, and the link itself (in that order):
@app.route('/download_csv')
def download():
return render_template('download_csv.html')
The above route works and I am able to navigate to the page with the link.
@app.route('/download_csv/')
def download_report():
conn = None
cursor = None
try:
curr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
curr.execute("SELECT id, username, league, team1, team2, team3, team4, team5, team6, team7, team8, team9, team10 FROM voting")
result = cursor.fetchall()
output = io.StringIO()
writer = csv.writer(output)
line = ['ID, League, Username, Team1, Team2, Team3, Team4, Team5, Team6, Team7, Team8, Team9, Team10']
writer.writerow(line)
for row in result:
line = [str(row['id']) + ',' + row['username'] + ',' + row['league'] + ',' + row['team1'] + ',' + row['team2'] + ',' + row['team3'] + ',' + row['team4'] + ',' + row['team5'] + ',' + row['team6'] + ',' + row['team7'] + ',' + row['team8'] + ',' + row['team9'] + ',' + row['team10']]
writer.writerow(line)
output.seek(0)
return Response(output, mimetype="text/csv", headers=("Content-Disposition:attachment;filename=power_ranking"))
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
When I click the link, I am receiving a Server 500 error, but am not sure why. I'm sure it has something to do with the first line of the last route; but not being familiar enough with Flask, I can't be certain. I do not know where to point that route; which is why it is 'download_csv/'
Thank you in advance.