烧瓶按钮可将查询中的表另存为csv

编程入门 行业动态 更新时间:2024-10-26 19:41:05
本文介绍了烧瓶按钮可将查询中的表另存为csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a flask app that runs a query and returns a table. I would like to provide a button on the page so the user can export the data as a csv.

问题在于查询是根据表单输入动态生成的.

The problem is that the query is generated dynamically based on form input.

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

On the html side it's just a simple table, looping over the rows and rendering them. I'm using bootstrap for styling, and included a tablesorter jquery plugin. None of this is really consequential. I did try one javascript exporter I found, but since my content is rendered dynamically, it saves a blank CSV.

我是否需要做一些ajax风格的骗术才能从路由中获取csv对象?

Do I need to do some ajax-style trickery to grab a csv object from the route?

推荐答案

我自己解决了这个问题.对于遇到此问题的任何人,我发现它对于烧瓶中的特定用例很有价值.这就是我所做的.

I solved this myself. For anyone who comes across this I find it valuable for the specific use case within flask. Here's what I did.

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

更多推荐

烧瓶按钮可将查询中的表另存为csv

本文发布于:2023-10-26 11:44:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530037.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:烧瓶   可将   另存为   按钮   csv

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!