[英]I want to export an Postgres Table as an CSV File as a download button on Flask. How to do that?
我的 PSQL 上有一個表,我想將它作為可下載文件導出給單擊下載按鈕的任何用戶,因此我的路徑不固定。 復制命令在這里對我不起作用。 任何解決方案?
@app.route("/")
@roles_required('member')
def index():
return render_template("pages/index.html")
@app.route("/download_csv")
@roles_required('member')
def download_csv():
conn = None
cursor = None
try:
conn = psycopg2.connect("host=localhost dbname=db user=u password=p")
cursor = conn.cursor()
cursor.execute('SELECT id FROM table')
# conn.commit()
result = cursor.fetchall() # fetchone()
output = io.StringIO()
writer = csv.writer(output)
line = ['column1,column2']
writer.writerow(line)
for row in result:
line = [row[0] + ' , ' + row[1] + ' , ']
writer.writerow(line)
output.seek(0)
return Response(output, mimetype="text/csv",
headers={"Content-Disposition": "attachment;filename=report.csv"})
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
索引.html
...
<a href="{{ url_for('app.download_csv') }}" style="margin-bottom: 10px; margin-left: 10px;" class="btn btn-primary" type="button">
Download Csv <i class="fa fa-file-csv"></i>
</a>
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.