如何正确导出Flask中的Postgres表



我已经创建了一个Heroku web应用程序作为个人项目,但由于我是Flask和SQL数据库的新手,所以一直遇到错误。

我创建了一个页面,显示用户在网站上输入的数据库(操作方式类似于管理员视图(。我的计划是有一个按钮/链接,可以将数据库表中当前的任何信息导出为CSV。

这里是HTML;下载CSV";链接-页面为"download_csv.html":

<body>
<h3>Download Power Rankings CSV Report</h3>
<p>
<a href={{ url_for('download_report') }}>Generate CSV Report</a>
</p>
</body>

我在app.py中创建的关于带有链接的页面和链接本身的路由(按顺序(:

@app.route('/download_csv')
def download():
return render_template('download_csv.html')

以上路线有效,我可以导航到带有链接的页面。

@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()

当我单击链接时,我收到一个Server500错误,但不确定原因。我确信这与最后一条线路的第一条线路有关;但我对弗拉斯克不够熟悉,我不能确定。我不知道该把那条路指向哪里;这就是为什么它是"download_csv/">

提前谢谢。

我把代码改成了这个,它实现了我想要实现的目标:

@app.route('/download_csv/report/excel')
def download_report():
curr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
curr.execute("SELECT * FROM voting")
result = curr.fetchall()
#for row in result:
#print(row)
#output in bytes
output = io.BytesIO()
#create WorkBook object
workbook = xlwt.Workbook()
#add sheet
sh = workbook.add_sheet('Power Rankings Report')
#add headers
sh.write(0, 0, 'ID')
sh.write(0, 1, 'Username')
sh.write(0, 2, 'League')
sh.write(0, 3, 'Team 1')
sh.write(0, 4, 'Team 2')
sh.write(0, 5, 'Team 3')
sh.write(0, 6, 'Team 4')
sh.write(0, 7, 'Team 5')
sh.write(0, 8, 'Team 6')
sh.write(0, 9, 'Team 7')
sh.write(0, 10, 'Team 8')
sh.write(0, 11, 'Team 9')
sh.write(0, 12, 'Team 10')
id = 0
for row in result:
sh.write(id+1,0, str(row['id']))
sh.write(id+1,1, row['username'])
sh.write(id+1,2, row['league'])
sh.write(id+1,3, row['team1'])
sh.write(id+1,4, row['team2'])
sh.write(id+1,5, row['team3'])
sh.write(id+1,6, row['team4'])
sh.write(id+1,7, row['team5'])
sh.write(id+1,8, row['team6'])
sh.write(id+1,9, row['team7'])
sh.write(id+1,10, row['team8'])
sh.write(id+1,11, row['team9'])
sh.write(id+1,12, row['team10'])
id += 1
workbook.save(output)
output.seek(0)
return Response(output, mimetype="application/ms-excel", headers={"Content-Disposition":"attachment;filename=power_rankings.xls"})

最新更新