sql - 用于将查询中的表保存为 csv 的 Flask 按钮

标签 sql csv flask export

我有一个运行查询并返回一个表的 flask 应用程序。我想在页面上提供一个按钮,以便用户可以将数据导出为 csv。

问题是查询是基于表单输入动态生成的。

@app.route('/report/<int:account_id>', methods=['GET'])
def report(account_id):
    if request == 'GET':
        c = g.db.cursor()
        c.execute('SELECT * FROM TABLE WHERE account_id = :account_id', account_id=account_id)
        entries = [dict(title=row[0], text=row[1]) for row in c.fetchall()]
        return render_template('show_results.html', entries=entries)

在 html 方面,它只是一个简单的表格,循环遍历行并呈现它们。我正在使用 bootstrap 进行样式设置,并包含一个 tablesorter jquery 插件。这些都不是真正重要的。我确实尝试过我找到的一个 javascript 导出器,但由于我的内容是动态呈现的,因此它保存了一个空白的 CSV。

我是否需要做一些 ajax 风格的技巧来从路由中获取一个 csv 对象?

最佳答案

我自己解决了这个问题。对于遇到此问题的任何人,我发现它对 Flask 中的特定用例很有值(value)。这就是我所做的。

import cx_Oracle      # We are an Oracle shop, and this changes some things
import csv
import StringIO       # allows you to store response object in memory instead of on disk
from flask import Flask, make_response # Necessary imports, should be obvious

@app.route('/export/<int:identifier>', methods=['GET'])
def export(load_file_id):
    si = StringIO.StringIO()
    cw = csv.writer(si)
    c = g.db.cursor()
    c.execute('SELECT * FROM TABLE WHERE column_val = :identifier', identifier=identifier)
    rows = c.fetchall()
    cw.writerow([i[0] for i in c.description])
    cw.writerows(rows)
    response = make_response(si.getvalue())
    response.headers['Content-Disposition'] = 'attachment; filename=report.csv'
    response.headers["Content-type"] = "text/csv"
    return response

关于sql - 用于将查询中的表保存为 csv 的 Flask 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33766499/

相关文章:

sql - Coldfusion Excel 导出

将 WAR 文件部署到 Liferay 时未创建 SQL 表

mysql - 将 XML 文件同步到 MySQL 数据库

javascript - D3条形图不解析csv

Python OpenSSL 给出握手失败

c# 与 SQL(ADO.Net 与其他?)

javascript - 将 CSV 文件转换为 JSON 字典?

python - 从特定目录在 python 中打开 csv 文件时出错

python - 使用 Flask 返回多个图像文件

python - celery |发现 Flask 错误 : expected a bytes-like object, AsyncResult