【问题标题】:I want to export an Postgres Table as an CSV File as a download button on Flask. How to do that?我想将 Postgres 表导出为 CSV 文件作为 Flask 上的下载按钮。怎么做?
【发布时间】:2020-10-19 07:05:04
【问题描述】:

我的 PSQL 上有一个表,我想将它作为可下载文件导出给单击下载按钮的任何用户,因此我的路径不固定。复制命令在这里对我不起作用。有什么解决办法吗?

【问题讨论】:

    标签: sql postgresql flask


    【解决方案1】:
    @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()
    

    index.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>
    
    ...
    

    【讨论】:

      猜你喜欢
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2015-07-13
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多